Your first script
A shell script is simply commands written into a text file, in order, for the shell to run one after another. Any command sequence you've typed more than a couple of times deserves to become a script.
Write a script
Create hello.sh with an editor such as nano or vim:
#!/bin/bash
# My first script
echo "Hello, $USER!"
echo "Today is $(date +%F) and you are in $(pwd)"
- The first line,
#!/bin/bash, is the shebang: it tells the system which program runs the file.#!/usr/bin/env bashis also common; it finds bash through PATH. - Lines starting with
#are comments and are not executed.
Run it
chmod +x hello.sh # needed once: make it executable
./hello.sh # run it; ./ means "in this directory"
Or hand it to bash without the execute permission:
bash hello.sh
Both ways run the script in a child process, so cd and variables inside it don't affect your terminal. If you need that, use source hello.sh (see "Processes" in the Basics).
Where to keep scripts
Put your everyday scripts in ~/bin and add it to PATH; then you can run them by name from anywhere:
mkdir -p ~/bin
mv hello.sh ~/bin/hello
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
hello