-
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.sh
To run a script, the full path must be specified. If the script is in your current working directory, use this notation:
./file.sh
The first line should have a "shebang" (#!
) which points to the interpreter.
#!/bin/bash
Alternatively, #!/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=hello
Several things to note. There are no spaces surrounding
=
. Simple strings don't need"
.
Use the dollar sign ($
) to reference variables.
echo $var
hello
Naming 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
.
-
$USER
username -
$HOME
home folder -
$PWD
current working directory
-
$?
exit status of last command.0
indicates success, anything else (usually1
) is abnormal. -
$0
the 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 fromcommand
is written toFILE
.-
command 2> FILE
: stderr fromcommand
is written toFILE
.
-
-
command >> FILE
: the output fromcommand
is appended to the end ofFILE
. -
command < FILE
: the content ofFILE
is used as input forcommand
. -
command1 && command2
:command2
runs ifcommand1
succeeds. -
command1 || command2
:command2
runs ifcommand1
fails. -
command1 | command2
: output fromcommand1
is piped to the input stream ofcommand2
.
if [ $var = "kitty" ]; then
echo meow
fi