Commands

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

aspell

Spell check a file.

● Check the file foo.txt: $ aspell check foo.txt

at
Schedule a command to run once at a particular time,

● Run the export1.sh script at 11pm:


$ echo "/home/scripts/export1.sh" | at 23:00

awk
Find and Replace text

● From an ls - l listing, return the fifth item ($5) from each line
of the output:

$ ls -l | awk '{print $5}'

● Print the Row Number (NR), then a dash and space ("- ") and
then the first item ($1) from each line in samplefile.txt:

$ awk '{print NR "- " $1 }' samplefile.txt

● Print the first item ($1) and then the third last item $(NF-2)
from each line in samplefile.txt:
$ awk '{print $1, $(NF-2) }' samplefile.txt
● Print every line that has at least one field.
awk 'NF > 0' data.txt
bg
Sends a job/process/task in the background

● put the job with job id 0 in the background: $ bg %0

bash
Open a new instance of the bash shell.

● Open a new bash shell: $ bash


● Exit the current shell, this will return to any previous parent
shell, or if none will exit the terminal session completely: $
exit

base32
Base32 encode/decode data and print to standard output.

● Encode the text file sample.txt: $ base32 sample.txt >


encoded.txt
● Decode the file encoded.txt: $ base32 -d encoded.txt >
restore.txt

cd
Change Directory - change the current working directory to a specific Folder.
● Move to the sybase folder: $ cd /usr/local/sybase

$ pwd

/usr/local/sybase

● Change to another folder: $ cd /var/log

$ pwd

/var/log

● Quickly get back: $ cd -

$ pwd

/usr/local/sybase

● Move up one folder: $ cd ..

$ pwd

/usr/local/

 Back to your home directory: $ cd


 Change to the directory fred inside the current directory: $ cd
./fred

chmod
Examples

chmod 400 file - Read by owner


chmod 040 file - Read by group
chmod 004 file - Read by world

chmod 200 file - Write by owner


chmod 020 file - Write by group
chmod 002 file - Write by world

chmod 100 file - execute by owner


chmod 010 file - execute by group
chmod 001 file - execute by world
To combine these, just add the numbers together:
chmod 444 file - Allow read permission to owner and group and
world
chmod 777 file - Allow everyone to read, write, and execute file

Some other examples:

Deny execute permission to everyone:


chmod a-x file

Allow read permission to everyone:


chmod a+r file

Make a file readable and writable by the group and others:


chmod go+rw file

Make a shell script executable by the user/owner


$ chmod u+x myscript.sh

You can then execute it like this: ./myscript.sh


chgrp
'chgrp' changes the group ownership of each given File to Group (which can be
either a group name or a numeric group id)

● Change the group ownership of a file to 'OpsGroup': $ chgrp OpsGroup


/usr/database/demo.dbf

● Change the group ownership of a directory and all sub-directories to


'OpsGroup', display all the changes made: $ chgrp -c -R OpsGroup
/usr/database/

here, -c is for verbosely printing the actions for those files


whole ownership has been changed.

and -R is for recursively changing the ownership for any


subdirectories under the mentioned directory.

cat
Concatenate and print (display) the content of files.

 Display a file: $ cat myfile.txt


 Display all .txt files: $ cat *.txt
 Concatenate two files: $ cat File1.txt File2.txt > union.txt

cut
Divide a file into several parts (columns)

 Cut from a single string -> echo "Lorem ipsum dolor sit amet"
| cut -d ' ' -f 2 [output: ipsum]
 Cut from a file -> to display the 1st and 3rd fields using “:” as
a delimiter:
cut test.txt -d ':' -f 1,3
 Parse out column 2 from a semicolon (;) delimited file:
$ cat myfile.txt | cut -d ‘;’ -f 2 > output.txt

cp [ source destination]
copy files and directories

 Copy file in current directory itself: $ cp viewers_list.txt


users_list.txt
 Copy a file in ‘backup’ directory: $ cp viewers_list.txt
backup/
 Copy in ‘backup’ directory with different name:
$ cp viewers_list.txt backup/viewers_list.bak
 Use -i option of cp command for interactive mode to prompt
before overwriting an existing file:
$ cp -i viewers_list.txt users_list.txt
cp: overwrite 'users_list.txt'? y

 Copy multiple files to a specified directory, in this case 'news':


$ cp current_news.txt headlines.txt cover_story.txt
news/
 Copy multiple files using wild card. It copies all files with
extension .txt to 'newsportal' directory:

$ cp *.txt newsportal/

df
Disk Free - display free disk space.

 List free disk space: df –h [-h is for human readable]

dir
 Briefly list directory contents.

 Syntax
Dir [Equivalent to 'ls -C -b']

diff
Display the differences between two files

 Character sort: $ sort countries.txt


 Numeric sort: $ sort -n numbers.txt

$ diff -q <(sort file1.txt | uniq) <(sort file2.txt | uniq)

The command above will return 0 if file1.txt = file2.txt

and will return 1 if file1.txt ≠ file2.txt.

Note the files have to be sorted first (the order matters) and if the
files could contain duplicate values, then the output of sort has to
be run through the uniq command to eliminate any duplicate
elements.
Echo
Display message on screen, writes each given STRING to standard
output, with a space between each and a newline after the last one.

 echo "Hello World"


 DEMO=Testing123
echo "$DEMO"
# Testing123

exit
Exit from a program, shell or log out of a Unix network.
Syntax
exit [n]

Key
n Set the exit status to n (default=0)

expr
Evaluate expressions, evaluates an expression and writes the result
on standard output.

Examples

# A partial match will return the number of characters that


match:
$ expr ss64 : ss6
3

# The condition in string 2 must entirely match string 1


$ expr ss64 : ss7
0

# Adding numbers
$ expr 5 + 2
7

# When multiplying the * has to be escaped


$ expr 5 \* 3
15

# Incrementing a variable (arithmetic expansion)


$ DEMO=1
$ DEMO='expr $DEMO + 1'
$ echo $DEMO
2
$ DEMO='expr $DEMO + 1'
$ echo $DEMO
3

find
The find command in UNIX is a command line utility for walking a
file hierarchy. It can be used to find files and directories and
perform subsequent operations on them. It supports searching by
file, folder, name, creation date, modification date, owner and
permissions. By using the ‘-exec’ other UNIX commands can be
executed on files or folders found.

 Search a file with pattern: $ find ./GFG -name *.txt [It will give
all files which have ‘.txt’ at the end.]
 Search a file with specific name: $ find ./GFG -name
sample.txt [It will search for sample.txt in GFG directory.]
 How to find and delete a file with confirmation: $ find ./GFG -
name sample.txt -exec rm -i {} \;
 Search for empty files and directories: $ find ./GFG –empty
[This command find all empty folders and files in the entered
directory or sub-directories.]

fg
Sends a job/process/task in the foreground

● Put the job with job id 0 in the foreground: $ fg %0

Fuser
Identify processes which are using files or sockets, optionally: Kill
the process that is accessing the file.

 Running fuser command without any option will displays the


PIDs of processes currently accessing your current working
directory: $ fuser
 You can determine which processes are accessing your
~.bashrc file like so: $ fuser -v -m .bashrc [-v is for verbose
and –m or -mount means name all processes accessing the file
NAME. In case you a spell out directory as NAME, it is
spontaneously changed to NAME/, to use any file system that
is possibly mounted on that directory.]
 Kill all processes accessing the file system /home in any way:
$ fuser -km /home
fgrep
Search file(s) for lines that match a fixed string

 $fgrep -c "usin.g" source.txt [Displaying the count of number


of matches]
 fgrep -h "usin.g" source.txt [To display the matched lines.]
 fgrep -i "geeks*forgeeks" source.txt [Used in case insensitive
search. It ignore upper/lower case distinction during
comparisons. It matches words like : “geeks*forgeeks”,
“Geeks*forgeeks”.]
 fgrep -l "geeks*forgeeks" source1.txt source2.txt [It will
display the file names that match the pattern]

grep
Search file(s) for specific text.

● Search the file example.txt, including binary data (-a) for the string 'hunting the
snark':
$ grep -a “hunting the snark” example.txt

● Search the whole partition (/sda1), including binary data(-a) for the string 'hunting
the snark' return all the lines starting 25 Before the text found and 50 lines After
the matching text found.
This can be a way to discover fragments of deleted files but is very slow:
$ grep -a -B 25 -A 50 “hunting the snark” /dev/sda1 >
results.txt

● Search the file wordlist.txt for any lines that include either 'sco' or 'sca':


$ grep "sc[oa]" wordlist.txt
● Search the file wordlist.txt for any lines that don't include at least one vowel:
$ grep -v [aeiou] wordlist.txt [-v : This prints
out all the lines that do not matches the pattern]

● Matching the lines that start with a string: The ^ regular expression pattern
specifies the start of a line. This can be used in grep to match the lines which
start with the given string or pattern.
$ grep "^unix" geekfile.txt

 Matching the lines that end with a string: The $ regular expression pattern
specifies the end of a line. This can be used in grep to match the lines which end
with the given string or pattern.

$ grep "os$" geekfile.txt

gzip
Compress or decompress named file(s)

 gzip filename
This will compress the file, and append a .gz extension to it. The
original file is deleted. To prevent this, you can use the -c option
and use output redirection to write the output to the filename.gz
file:
 gzip -c filename > filename.gz [The -c option specifies that
output will go to the standard output stream, leaving the
original file intact]
 You can compress multiple files by listing them: gzip
filename1 filename2
 You can compress all the files in a directory, recursively, using
the -r option: gzip -r a_folder
 gzip can also be used to decompress a file, using the -d
option: gzip -d filename.gz
head
output the first part of files, prints the first part (10 lines by
default) of each file.
 Extract the first 85 lines from a file: head –n 85 file.txt
 Extract lines 40-50 from a file, first using head to get the first
50 lines then tail to get the last 10: head -50 file.txt | tail -10

history
Command Line history.

 Clear the history list: history –c


 Append the new history lines (history lines entered since the
beginning of the current Bash session) to the history file:
history –a
 Write out the current history to the history file.: history –w

ifconfig
Interface configurator
 Change the state of the network interface device(s) to UP:

$ ifconfig eth0 up
 Change the state of the network interface device(s) to DOWN:
(see also ip link):
$ ifconfig eth0 dn

Here, eth0 = 1st Ethernet interface.

ip
 show all IP addresses associated on all network devices :
$ ip address

ifup / ifdown
Bring a network interface up or down
 Bring up all the interfaces defined with auto in /etc/network/interfaces :

ifup -a

 Bring up interface eth0:

ifup eth0

 Bring down all interfaces that are currently up:

ifdown -a

Jobs
Check background processes
killall
Kill processes by name.

 Kill firefox using killall : $ killall -9 mozilla-bin


Here, 9 is for SIGKILL which means kill the signal.

 Kill firefox using kill: $ kill -9 $(pidof firefox)

ls
List information about files.

 List the contents of your home directory: $ ls ~


 To show all the hidden files in the directory: $ ls -a
 List the directories in the current directory: $ ls -d */
 List all subdirectories: $ ls *
Locate
Find files.

 Search a file with specific name: $ locate sample.txt [It will


search for sample.txt in particular directory.]
 Limit Search Queries to a Specific Number:
$ locate "*.html" -n 20 [It will show 20 results for the
searching of file ending with .html]
 Display The Number of Matching Entries: $ locate -c [.txt]*

[It will count files ending with .txt.]

 Ignore Case Sensitive Locate Outputs. This command is


configured to process queries in a case sensitive manner. It
means SAMPLE.TXT will show a different result than
sample.txt. : $ locate -i *SAMPLE.txt*

mv
Move or rename files or directories.

 Rename the file apple as orange.doc: mv apple orange.doc


 Move orange.doc to the Documents folder: mv orange.doc
~/Documents/orange.doc

mkdir
Create new folder(s), if they do not already exist.
 Create the folder 'demo': $ mkdir demo

pwd
Print Working Directory.

 The pathname printed will not contain symbolic link:$ pwd –P


 The pathname printed will contain symbolic link:$ pwd -L

rm
Remove files (delete/unlink).

 Remove demo.txt: rm demo.txt


 Remove demo1.txt and demo2.txt: rm demo1.txt
demo2.txt
 Remove all the .txt files in the current directory and prompt
before each deletion: rm -i *.txt [here, -i is for Prompt
before every removal]
 Remove all the files from the current directory apart from
text.txt: rm -f !(test.txt) [here, -f is for force and
also ignoring non existing files.]
rmdir
Remove directory, this command will only work if the folders are
empty.

$ rmdir myfolder

sort
Sort text files.

 Character sort: $ sort countries.txt


 Numeric sort: $ sort -n numbers.txt
 Sort in descending (reverse) numeric order: $ sort -nr
 To sort the file below on the third field (area code):
Jim Alchin 212121 Seattle
Bill Gates 404404 Seattle
Steve Jobs 246810 Nevada
Scott Neally 212277 Los Angeles
$ sort -k 3,3 people.txt> sorted.txt

-k, --key=POS1[,POS2]
Start a key at POS1 (origin 1), end it at POS2 (default end of line).

tail
Output the last part of files, print the last part (10 lines by default)
of each FILE.

 Extract the last 85 lines from a file: $ tail –n 85 file.txt


touch
Change file timestamps, change the access and/or modification times of
the specified files.
 Create/datestamp one file called sample.txt: $ touch sample.txt
 Create/datestamp one file called sample.txt in a subfolder:
touch "some folder/sample.txt"
 Touch command Syntax to create a new file: $ touch file_name
 Touch command to create multiple files: $ touch File1_name
File2_name File3_name

&
Starts a new job/process in the background.

● To start a new process in the background you can do:


$ long_running_command &
======================================

Basically, there are two different commands to create a file in the


Linux system which is as follows:

 cat command: It is used to create the file with content.


 touch command: It is used to create a file without any content.
The file created using touch command is empty. This
command can be used when the user doesn’t have data to
store at the time of file creation.

You might also like