Linux Commands and Shell Scripting
- Getting Information
- Navigating and working with files and directories
- Printing file and string contents
- Compression and archiving
- Performing network operations
- Monitoring performance and status
- Running batch jobs
Linux and Bash Command Cheat Sheet: The Basics
Getting information
# return your user namewhoami
# return your user and group idid
# return operating system name, username, and other infouname -a
# display reference manual for a commandman top
# get help on a commandcurl --help
# return the current date and timedate
The following command displays current date in mm/dd/yy format.
date "+%D"Here are some of the popular format specifiers that you can try out.
Specifier | Explaination |
---|---|
%d | Display the day of the month (01 to 31) |
%h | Displays abbreviated month name (Jan to Dec) |
%m | Displays the month of year (01 to 12) |
%Y | Display four-digit year |
%T | Display the time in 24 hour format as HH:MM:SS |
%H | Display the hour |
Monitoring performance and status
# list selection of or all running processes and their PIDsps
ps -e
# display resource usagetop
- Summary Area. - shows information like system uptime, number of users, load average, memory usage
- Fields/Columns Header.
- Task Area.
Using 'top' we can find out which process is consuming the most resources, can press the following keys while 'top' is running to sort the list :
M - sort by memory usage
P - sort by CPU usage
N - sort by process ID
T - sort by the running time
# list mounted file systems and usagedf
Working with files
# copy a filecp file.txt new_path/new_name.txt
# change file name or pathmv this_file.txt that_path/that_file.txt
# remove a file verboselyrm this_old_file.txt -v
# create an empty file, or update existing file's timestamptouch a_new_file.txt
# change/modify file permissions to 'execute' for all userschmod +x my_script.sh
Option | Description. |
---|---|
r, w and x | representing read, write and execute permissions respectively |
u,g and o | representing user categories owner, group and others respectively |
+, - | representing grant and revoke operations respectively |
# get count of lines, words, or characters in filewc -l table_of_data.csv
wc -w my_essay.txt
wc -m some_document.txt
# return lines matching a pattern from files matching a filename pattern - case insensitive and whole words onlygrep -iw hello \*.txt
# return file names with lines matching the pattern 'hello' from files matching a filename patterngrep -l hello \*.txt
Navigating and working with directories
# list files and directories by date, newest lastls -lrt
Here are some popular options to try with the ls command.
Option | Description |
---|---|
-a | list all the files including hidden files |
-d | list directories themselves, not their contents |
-h | with -l and -s, print sizes like 1K, 234M, 2G etc |
-l | long listing of files which include information about permission, owner, size etc |
-F | classify files by appending type indcator like *,/ etc. to file names |
-r | reverse order while sorting |
-S | sort by file size, largest first |
-t | sort by time, newest first |
# find files in directory tree with suffix 'sh'find -name '\*.sh'
# return present working directorypwd
# make a new directorymkdir new_folder
# change the current directory: up one level, home, or some other pathcd ../
cd ~
or cd
cd another_directory
# remove directory, verboselyrmdir temp_directory -v
Printing file and string contents
# print file contentscat my_shell_script.sh
# print file contents page-by-pagemore ReadMe.txt
# print first N lines of filehead -10 data_table.csv
# print last N lines of filetail -10 data_table.csv
# print string or variable valueecho "I am not a robot"
echo "I am $USERNAME"
Compression and archiving
# archive a set of filestar -cvf my_archive.tar.gz file1 file2 file3
# compress a set of fileszip my_zipped_files.zip file1 file2
zip my_zipped_folders.zip directory1 directory2
# extract files from a compressed zip archiveunzip my_zipped_file.zip
unzip my_zipped_file.zip -d extract_to_this_direcory
Performing network operations
# print hostnamehostname
# send packets to URL and print responseping www.google.com
# display or configure system network interfacesifconfig
ip
# display contents of file at a URLcurl <url>
# download file from a URLwget <url>
Bash shebang
#!/bin/bash
Pipes and Filters
# chain filter commands using the pipe operatorls | sort -r
# pipe the output of manual page for ls to head to display the first 20 linesman ls | head -20
Shell and Environment Variables
# list all shell variablesset
# define a shell variable called my_planet and assign value Earth to itmy_planet=Earth
# display shell variableecho $my_planet
# list all environment variablesenv
# environment vars: define/extend variable scope to child processesexport my_planet
export my_galaxy='Milky Way'
Metacharacters
# comments# The shell will not respond to this message
# command separatorecho 'here are some files and folders'; ls
# file name expansion wildcardls *.json
# single character wildcardls file_2021-06-??.json
Quoting
# single quotes - interpret literallyecho 'My home directory can be accessed by entering: echo $HOME'
# double quotes - interpret literally, but evaluate metacharactersecho "My home directory is $HOME"
# backslash - escape metacharacter interpretationecho "This dollar sign should render: \$"
Special Character | Meaning |
---|---|
\n | Represents a newline character |
\t | A tab character |
I/O Redirection
# redirect output to fileecho 'Write this text to file x' > x
# append output to fileecho 'Add this line to file x' >> x
# redirect standard error to filebad_command_1 2> error.log
# append standard error to filebad_command_2 2>> error.log
# redirect file contents to standard input$ tr “[a-z]” “[A-Z]” < a_text_file.txt
# the input redirection above is equivalent to$cat a_text_file.txt | tr “[a-z]” “[A-Z]”
Command Substitution
# capture output of a command and echo its valueTHE_PRESENT=$(date)
echo "There is no time like $THE_PRESENT"
Command line arguments
./My_Bash_Script.sh arg1 arg2 arg3
Batch vs. concurrent modes
# run commands sequentiallystart=$(date); ./MyBigScript.sh ; end=$(date)
# run commands in parallel./ETL_chunk_one_on_these_nodes.sh & ./ETL_chunk_two_on_those_nodes.sh
Scheduling jobs with Cron
# open crontab editorcrontab -e
# job scheduling syntaxm h dom mon dow command
minute, hour, day of month, month, day of week*
means any
# append the date/time to file every Sunday at 6:15 pm15 18 * * 0 date >> sundays.txt
# run a shell script on the first minute of the first day of each month1 0 1 * * ./My_Shell_Script.sh
# back up your home directory every Monday at 3 am0 3 * * 1 tar -cvf my_backup_path\my_archive.tar.gz $HOME\
# deploy your cron job
Close the crontab editor and save the file
# list all cron jobscrontab -l
Comments
Post a Comment