2017年5月3日 星期三

bash

  • $0 - The name of the Bash script.
  • $1 - $9 - The first 9 arguments to the Bash script. (As mentioned above.)
  • $# - How many arguments were passed to the Bash script.
  • $@ - All the arguments supplied to the Bash script.
  • $? - The exit status of the most recently run process.
  • $$ - The process ID of the current script.
  • $USER - The username of the user running the script.
  • $HOSTNAME - The hostname of the machine the script is running on.
  • $SECONDS - The number of seconds since the script was started.
  • $RANDOM - Returns a different random number each time is it referred to.
  • $LINENO - Returns the current line number in the Bash script.
type command env to see list of variables.


variable values in single quote or double quote:
  • Single quotes will treat every character literally.
  • Double quotes will allow you to do substitution (that is include variables within the setting of the value). e.g. echo "Hello $username"
read user input
read varname
read -p 'Username:' varname
read -sp 'Password: ' passvar

$((a+3)) - $(( ... )) return result of expression
${#a} - return length of variable

if statement
if [ $1 -gt 100 ]
then
  echo 'greater than 100'
elif
  echo 'else if'
else
  echo 'smaller than 100'
fi

Operator Description
! EXPRESSION The EXPRESSION is false.
-n STRING The length of STRING is greater than zero.
-z STRING The lengh of STRING is zero (ie it is empty).
STRING1 = STRING2 STRING1 is equal to STRING2
STRING1 != STRING2 STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2 INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is numerically less than INTEGER2
-d FILE FILE exists and is a directory.
-e FILE FILE exists.
-r FILE FILE exists and the read permission is granted.
-s FILE FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE FILE exists and the write permission is granted.
-x FILE FILE exists and the execute permission is granted.

case statement
case <variable> in
<pattern 1>)
<commands>
;;
<pattern 2>)
<other commands>
;;
esac


while loop
while [ <some test> ]
do
<commands>
done

for loop
names='Stan Kyle Cartman'
for name in $names
do
   echo $name
done

for value in {1..5}  #basic range for loop
for value in {0..10..2} #add 2 each time
for value in {10..0..2} #deduct 2 each time

select - create simple menu
menuItems='Action1 Action 2 Action3 Quit'

PS3='your selection is: '  #change value of system variable PS3 so the prompt look more descriptive.

select item in $menuItems
do
   if [ $item == 'Quit' ]
   then
       break
   fi
   echo Action: $item
done
echo Bye

沒有留言:

張貼留言