Automation Scripts
In ML_Tools, see: Bash_folder
Basic Commands
- Show Current Directory:
pwd - Display Contents of a Text File:
cat filename.txt - Search for a Word in a File:
[[grep]] "word" filename.txt - Replace Text in a File (Output Only):
sed 's/old/new/g' filename.txt
Writing and Running a Bash Script
-
Create a Script:
nano hello.shAdd:
#!/bin/bash echo "Hello, $(whoami)! Welcome to Bash scripting!"Save and exit: Ctrl + O, Enter, Ctrl + X.
-
Make the Script Executable:
chmod +x hello.sh -
Run the Script:
./hello.sh
Useful Bash Automation Tips
- Clear Screen:
clear - Keyboard Shortcut: Ctrl + L.
- Clear Screen and Command History:
clear && history -c - Reset Terminal:
reset
Managing Command History
- Clear Current Session’s History:
history -c - Save History to a Custom File:
history > my_session_history.txt - Clear and Remove Saved History:
history -c > ~/.bash_history - Start a Fresh Bash Session:
exec bash
Example: Conditional Execution
if [ -f filename.txt ]; then
echo "File exists."
else
echo "File does not exist."
fiIf you want to learn more bash, explore:
See these concepts:
- Shebang:
#!/bin/bash - Variables:
$PI_IP,${variable} - Conditionals:
if [ condition ]; then - Loops:
for,while - Functions:
function_name() {} - Command substitution:
$(command) - Redirects:
>,>>,2>&1
See these concepts:
- Function definitions and exports
- Color codes (ANSI escape sequences)
- Command piping:
| - SSH with command execution
- Error checking:
$? - Configuration files
- Heredocs:
<< 'EOF'