How to Execute Shell Scripts
How to Execute Shell Scripts
1. Prerequisites
Before running the scripts, ensure the following:
cd /path/to/scripts/
3. Verify Script Files: Use the ls command to list the scripts in the directory:
ls
ls -l script_name.sh
Look for the x (executable) flag in the file's permissions.
2. Add Execute Permission (if needed): If the x flag is missing, make the script
executable:
chmod +x script_name.sh
./script_name.sh
bash script_name.sh
or
sh script_name.sh
2. Optional - Run with Sudo: If the script requires administrative privileges, prepend the
command with sudo :
sudo ./script_name.sh
6. Troubleshooting Errors
1. Check the Output: Review the terminal output for any error messages or prompts.
2. Common Issues:
Missing dependencies: Install them using your package manager (e.g., apt , yum ,
or brew ).
Incorrect paths: Double-check file and directory paths.
3. Debugging: Add -x to the script execution for debugging:
bash -x script_name.sh
crontab -e
0 10 * * * /path/to/script_name.sh
Windows Task Scheduler: Schedule the script using the Windows Task Scheduler for
automation.
8. Exit Codes
After execution, check the exit code to confirm success:
echo $?
0 indicates success.
Any non-zero value indicates an error.
Example:
Script: backup.sh
Purpose: Backup the home directory to an external drive.
Dependencies: rsync, external drive mounted at /mnt/backup.
Inputs: None.
Outputs: Backup logs stored in /var/log/backup.log.
Expected Outcome: The home directory is backed up without errors.