Linux Shell Notes

Presenter

Herbert Kudakwashe Nguruwe (Kuda)
HPC Specialist (UKAEA – Oxford, UK)


Code of Conduct – Software Carpentries


Course Outline


Install and Download


What is Shell?


Why Do We Care?

Example Prompt:

IP-10-215-129-174:~ vg9053$ 


Paths


Working with Files and Directories

# Create
mkdir thesis
mkdir -p ../project/data ../project/results

# Edit
cd thesis
nano draft.txt
touch my_file.txt

# Move and rename
mv thesis/draft.txt thesis/quotes.txt
mv statstics.txt statistics.txt

# Copy
cp quotes.txt thesis/quotations.txt
cp -r thesis thesis_backup

# Remove
rm quotes.txt
rm -i thesis_backup/quotations.txt

Operations with Multiple Files and Wildcards

cp creatures/minotaur.dat creatures/unicorn.dat backup/

# Wildcards
# * matches zero or more characters
# ? matches exactly one character

Pipes and Filters

wc -l *.pdb > lengths.txt      # Redirect output
sort -n lengths.txt | head -n 1
history | grep rm
wc -l *.txt | sort -n | tail -n 5

Loops

for file in *.pdb
do
  echo $file
done

Symbols and Their Meaning


Shell Scripts

# Create a script
nano middle.sh

# Add this
head -n 15 octane.pdb | tail -n 5

# Save and exit
Ctrl + O
Ctrl + X

# Run the script
bash middle.sh

# Modify to accept arguments
head -n "$2" "$1" | tail -n "$3"

# Full example with parameters and comments
# middle.sh
# Usage: bash middle.sh filename num1 num2

head -n "$2" "$1" | tail -n "$3"

Shell Scripts Continued

# sorted.sh
nano sorted.sh

# Add this
# Sort files by their length.
# Usage: bash sorted.sh file1 file2 ...
wc -l "$@" | sort -n

# Run it
bash sorted.sh *.pdb ../creatures/*.dat

Finding Things Using Grep

grep "The" haiku.txt
grep --help
man grep

Finding Things Using Find

find .
find . -type d
find . -type f
find . -name numbers.txt
wc -l $(find . -name "*.txt")
grep "searching" $(find . -name "*.txt")
wc -l $(find . -name "*.dat") | sort -n

End of Shell Tutorial

Questions?

Additional Resources: