pwd = print working directory COMMAND > FILE: execute COMMAND and the output rewrites the FILE COMMAND >> FILE: execute COMMAND and the output concates the FILE LCOMMAND | RCOMMAND: (pipe) use the output of left command as the input of right command
Shell script
‘’ and “”
1 2 3 4 5
foo=bar echo "$foo" # prints bar echo '$foo' # prints $foo
$
$1 to $9 - Arguments to the script. $1 is the first argument and so on.
$@ - All the arguments
$? - Return code of the previous command
!! - Entire last command, including arguments. A common pattern is to execute a command only for it to fail due to missing permissions; you can quickly re-execute the command with sudo by doing sudo !!
$_ - Last argument from the last command. If you are in an interactive shell, you can also quickly get this value by typing Esc followed by .
example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/bin/bash
echo "Starting program at $(date)" # date is a command
echo "Running program $0 with $# arguments with pid $$"
for file in "$@"; do grep foobar "$file" > /dev/null 2> /dev/null # When pattern is not found, grep has exit status 1 # We redirect STDOUT and STDERR to a null register since we do not care about them if [[ $? -ne 0 ]]; then echo "File $file does not have any foobar, adding one" echo "# foobar" >> "$file" fi done
{}
1 2
mv *{.py,.sh} folder # Will move all *.py and *.sh files
<(CMD): save the output in a temporary file, and return the file name
1 2
# Show differences between files in foo and bar diff <(ls foo) <(ls bar)
#! shebang
used to select the interpreter of the code (if python script, then the interpreter should be python)
#!/usr/bin/env python3 – Execute with a Python interpreter, using the env program search path to find it
#!/bin/bash – Execute the file using the Bash shell
find
1 2 3 4
# Delete all files with .tmp extension find . -name '*.tmp' -exec rm {} \; # Find all PNG files and convert them to JPG find . -name '*.png' -exec convert {} {}.jpg \;
Others
sed : a command that edits file without opening it