Anna Syme

Click name ↑ to return to homepage

Basic bash script

Open the terminal.

mkdir bash-scripts
cd bash-scripts

in, write (some or all):

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

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

# 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
bash #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 #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
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 ./ or bash
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 #runs the script with bash
bash 25 Tuesday #two cmd line args as well


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