Quick BASH Commands
Quick BASH Commands
1. Search for Files Recursively To Find an Expression
This command will list all filenames containing the string nltk:
$ find . -type f -exec grep -l "nltk" {} \;Note that the -l option lists the filenames only.
2. Print the Elapsed Time of Code Execution
This script is useful when you want to track the code execution’s time:
3. Search and Replace Strings in Files
This command will replace strings equal to localhost:8000 with localhost:8080 in all files:
$ find . -type f -exec grep -l "localhost:8000" {} \; | xargs sed -i 's/localhost:8000/localhost:8080/g'4. Delete Specific Files
- This command deletes all empty files ending with
.log:
$ find . -type f -name "*.log" -exec rm {} \;- To delete all files older than 25 days, run this command:
$ find . -type f -mtime +25 -exec rm {} \;5. Execute Command on Each File if a Condition Is Met
This script loops through all files in the current directory and checks if the filename starts with a letter. If the condition is met, it executes an echo command in this example:
6. Download Files From a Remote Server
Use this command to download a file from a server and save it locally:
$ scp username@server:path/to/file destination_path7. Upload Files to a Remote Server
Copy a local directory to a remote server:
$ scp -r /local/dir username@server:/remote/dirThis command uploads a local file to a server under a new filename:
$ scp file.txt username@server:/remote/dir/newfilename.txt8. Copy Files Between Two Remote Servers
$ scp user1@server1:/dir1/file.txt user2@server2:/dir29. Pass an Argument to a Script
If you want to pass a command-line argument to a script, use this syntax in the script:
echo "The first argument is: $1"Execution:
./myscript.sh myargumentIf you need a second argument, use $2, and so on.
10. Assign a Variable to a Command Result
You can use command substitution to make a variable equal to the output of another command. For example, the code below sends an email to the currently logged on user retrieved by the logname command:
Conclusion
In this article, I introduced some handy and frequently used Linux scripts/commands. Having ready-to-use templates can save a lot of work.