Linux basics session 5
Bash scripting
- bash script is a file with list of commands to be executed, by convention we name files ending ".sh", we've created a "script.sh" file by recalling a command in prompt, surrounding it with echo command and redirecting into a file:
echo "
" > script.sh" chmod +x script.sh
- scripts in general needs to have executable flag listed (to check runls -la
) "#!/bin/bash" needs to be on the first line in the file (use editor nano to add it to our file), this decides on how the script will be interpreted (we will put Python here later), this line is called hashbang - https://en.wikipedia.org/wiki/Shebang_(Unix) - if all above is set run
./script.sh
to execute the script - script with variables
#//usr/bin/bash
user='vasek'
echo "Hi ${user}"
env
- lists all environment variables, for example current shell $SHELL, or current user $USER (letter case matters!), these variables are available always
for previous example is better to reuse system value `echo "Hi $USER"
example how to use subcommand return value as input insert one line from "words" file as a name: user="$(head -100 words | tail -1)"
Bash allows if conditions, loops and other programming tools, but writing bash scripts can easily become tedious due to strong syntax rules (different behavior for quotes and apostrophes just to mention one) and the fact that all variables are treated as text by default. Usually bash scripts are used for parameterized execution and scheduling of other command line tools.
Python scripting
Is better suited for data manipulation in many ways and offer strong scientific tooling. Similarly a script file needs to have executable flag enabled, but on the first line use different hashbang. Example script to extract latest events from github using API:
#!/usr/bin/env python3
import requests
r = requests.get('https://api.github.com/events')
print('Last github events:")
for item in r.json()
print(item['actor']['login']
Thinking excercise How would you create a script that outputs current timestamp and random line from file words? How do you store result in a text file?