Anna Syme

Click name ↑ to return to homepage

Basic bash script

Open the terminal.

mkdir bash-scripts
cd bash-scripts
nano script1.sh  

in script1.sh, write (some or all):

#!/usr/bin/env bash
echo here is my script

# set up logfile
now=$(date +%Y_%m_%d_%H_%M)
logfile="$now.txt"

# redirect stdout/stderr to logfile
exec &> $logfile

# print info in logfile
echo "log file for $0"
# $0 is the script name
echo "year_month_day_hour_minute $now"

# run another bash script
echo now running script2.sh
bash script2.sh #runs script2 if it exists

# run a python command
echo now printing hello using python
python -c "print('hello')"
#prints hello to screen, using python
#note the different quotation marks

# run a python script
echo now running a python script
python python-script.py #runs python-script

# activate a conda environment
echo now activating the conda env porechop
source activate porechop #activates the conda environment called porechop
#note, in a script: uses "source", not "conda"
echo now printing the porechop help info
porechop -h #prints the help info from porechop

# get user input
echo Please enter your name
read NAME
#stores user input in variable called NAME
echo "Hi $NAME!" #gets this variable by using $

# set variables
echo now setting var1 and var2
var1=Hello #sets a variable; note no spaces
var2=Person
echo now calling var1 and var2
echo $var1 $var2 #calls these variables

# set a variable for a directory location
mydir="./myfiles" #sets a variable which is this directory
echo now showing the directory saved as a variable called mydir
echo $mydir

# set a variable for the output of a command
var4=$(ls $mydir) #var4 is the output of that command
echo The files in $mydir are $var4

# variables for command line args
# these are cmd line args 1 and 2, entered after ./script1.sh or bash script.sh
echo what are command line args 1 and 2
echo command line arg1 is
echo $1
echo command line arg2 is
echo $2

Exit nano with Ctrl-X

bash script1.sh #runs the script with bash
bash script1.sh 25 Tuesday #two cmd line args as well

or

chmod 755 script1.sh #make the file executable
./script1.sh #runs an executable script
./script1.sh 25 Tuesday #two cmd line args as well