-
Notifications
You must be signed in to change notification settings - Fork 1
Shell scripting
Shell scripts should have the file extension .sh.
You must mark a file with the eXecutable permission to run it with this command:
chmod +x file.shTo run a script, the full path must be specified. If the script is in your current working directory, use this notation:
./file.shThe first line should have a "shebang" (#!) which points to the interpreter.
#!/bin/bashAlternatively, #!/bin/bash -e can be used to tell bash to quit on the first error. -x will cause bash to print commands and their arguments as they are executed.
"Naked variables" are initialized with the assignment operator.
var=helloSeveral things to note. There are no spaces surrounding
=. Simple strings don't need".
Use the dollar sign ($) to reference variables.
echo $var
helloNaming convention: environment variables and constants should be IN_ALL_CAPS. Temporary variables used in scripts should be in_lower_case. Space with underlines (don't use camelCase).
You can display all the current environment variables with the command printenv.
-
$USERusername -
$HOMEhome folder -
$PWDcurrent working directory
-
$?exit status of last command.0indicates success, anything else (usually1) is abnormal. -
$0the invoked command itself. -
$1,$2,$3... line parameters following the command. -
$*every parameter as a single string, separated by spaces. -
$@array of every parameter
A comment starts with #.
A command's output can be considered a string in another command's arguments using a subshell.
rm $(ls | grep "*.docx$") # deletes all *.docx files from the current directory.-
command > FILE: the output fromcommandis written toFILE.-
command 2> FILE: stderr fromcommandis written toFILE.
-
-
command >> FILE: the output fromcommandis appended to the end ofFILE. -
command < FILE: the content ofFILEis used as input forcommand. -
command1 && command2:command2runs ifcommand1succeeds. -
command1 || command2:command2runs ifcommand1fails. -
command1 | command2: output fromcommand1is piped to the input stream ofcommand2.
if [ $var = "kitty" ]; then
echo meow
fi