Create and run a Bash script
What is a shell script?
A shell script is a text file containing commands for a shell to read. Saving commands lets you run them again without typing each command separately. The .sh extension is a helpful naming convention, not a requirement for Bash. Use a plain-text editor, not a word processor that saves rich formatting.
Prepare a dedicated folder
Choose a writable location, such as your home directory. Use a fresh folder named bytemind-bash-lab; if it already exists, choose another unused name and use that name in both commands. mkdir creates a folder; cd changes the current working directory. Here && means run the next command only if the previous one succeeds. Continue with the file-creation step only after you see Lab ready.
mkdir bytemind-bash-lab && cd bytemind-bash-lab && printf '%s\n' 'Lab ready'Expected output when executed:
Lab readySave your first script
In that folder, create a new plain-text file called hello.sh using your editor. Save the following two lines exactly as file contents, with ordinary straight quotes. Use LF line endings if your editor lets you choose.
printf '%s\n' 'Hello from a script'printf '%s\n' 'Ready to learn'Expected output when executed:
Hello from a scriptReady to learnExpected output when executed:
Hello from a scriptReady to learnHello from a scriptReady to learnbash hello.sh starts Bash and tells it to read the file. The script prints two lines per invocation. Bash needs to be able to read the file, but the file itself does not need execute permission for this form. A path such as bash ./hello.sh explicitly selects the file in the current folder rather than allowing a PATH lookup if the bare name is absent. The next lesson explains direct execution.
When the file cannot be found
If Bash reports that the file does not exist, check the editor’s saved filename and the terminal’s current folder. pwd displays the current working directory; use it to compare with the editor location. Do not solve a wrong filename by changing permissions or using administrator privileges.
Practice
Create a separate file named report.sh in your lab folder. Make it print Report started then Report finished. Run it twice and compare the output.
Next lesson: Shebangs and script permissions