Skip to content
basaam0 edited this page Jun 9, 2018 · 1 revision

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.

Variables

"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).

Common environment variables

You can display all the current environment variables with the command printenv.

  • $USER username
  • $HOME home folder
  • $PWD current working directory

Special script variables

  • $? exit status of last command. 0 indicates success, anything else (usually 1) 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

Syntax

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.

Pipes (I/O redirection) and Basic Logic

  • command > FILE: the output from command is written to FILE.
    • command 2> FILE: stderr from command is written to FILE.
  • command >> FILE: the output from command is appended to the end of FILE.
  • command < FILE: the content of FILE is used as input for command.
  • command1 && command2: command2 runs if command1 succeeds.
  • command1 || command2: command2 runs if command1 fails.
  • command1 | command2: output from command1 is piped to the input stream of command2.

Control Flow

if [ $var = "kitty" ]; then
  echo meow
fi