Linux commands with output

BASH command output to the variable

Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs any command from the terminal then it shows the output if no error exists otherwise it shows the error message. Sometimes, the output of the command needs to be stored in a variable for future use. Shell command substitution feature of bash can be used for this purpose. How you can store different types of shell commands into the variable using this feature is shown in this tutorial.

Command Substitution Syntax:

***Note: Don’t use any space before and after the equal sign when using the above commands.

Single command output to a variable

Bash commands can be used without any option and argument for those commands where these parts are optional. The following two examples show the uses of simple command substitution.

Example#1:

bash `date` command is used to show the current date and time. The following script will store the output of `date` command into $current_date variable by using command substitution.

Output:

Example#2:

`pwd` command shows the path of the current working directory. The following script stores the output of `pwd` command into the variable, $current_dir and the value of this variable is printed by using `echo` command.

Output:

Command with option and argument

The option and argument are mandatory for some bash commands. The following examples show how you can store the output of the command with option and argument into a variable.

Example#3:

Bash `wc` command is used to count the total number of lines, words, and characters of any file. This command uses -c, -w and -l as option and filename as the argument to generate the output. Create a text file named fruits.txt with the following data to test the next script.
fruits.txt

Run the following commands to count and store the total number of words in the fruits.txt file into a variable, $count_words and print the value by using `echo` command.

Output:

Example#4:

`cut` is another bash command that uses option and argument to generate the output. Create a text file named weekday.txt with seven-weekday names to run the next script.

weekday.txt

Create a bash file named cmdsub1.sh with the following script. In this script, while loop is used to read the content of weekday.txt file line by line and read the first three characters of each line by using `cut` command. After cutting, the string value is stored in the variable $day. Next, If the statement is used to check the value of $day is ‘Sun’ or not. The output will print ‘Sunday is the holiday‘ when if the condition is true otherwise it will print the value of $day.

cmdsub1.sh

Output:

Using command substitution in loop

You can store the output of command substitution into any loop variable which is shown in the next example.

Example#5:

Create a file named cmdsub2.sh with the following code. Here, `ls -d */` command is used to retrieve all directory list from the current directory. For loop is used here to read each directory from the output and store it in the variable $dirname which is printed later.

cmdsub2.sh

Output:

Using nested commands

How you can use multiple commands using pipe(|) is shown in the previous example. But you can use nested commands in command substitution where the output of the first command depends on the output of the second command and it works opposite of the pipe(|) command.

Nested command syntax:

Example#6:

Two commands, `echo` and `who` are used in this example as the nested command. Here, `who` command will execute first that print the user’s information of the currently logged in user. The output of the `who` command will execute by `echo` command and the output of `echo` will store into the variable $var. Here, the output of `echo` command depends on the output of `who` command.

Читайте также:  Как открыть переменные среды windows 10

Output:

Using Command path

If you know the path of the command then you can run the command by specifying the command path when using command substitution. The following example shows the use of command path.

Example#7:

`whoami` command shows the username of the currently logged in user. By default, this command is stored in /usr/bin/ folder. Run the following script to run `whoami` command using path and store in the variable, $output, and print the value of $output.

Output:

Using Command Line argument

You can use the command line argument with the command as the argument in the command substitution.

Example#8:

Create a bash file named cmdsub3.sh with the following script. `basename` command is used here to retrieve the filename from the 2 nd command line argument and stored in the variable, $filename. We know the 1 st command line argument is the name of the executing script which is denoted by $0.

Run the script with the following argument value.

Here, the basename of the path, Desktop/temp/hello.txt is ‘hello.txt’. So, the value of the $filename will be hello.txt.

Output:

Conclusion:

Various uses of command substitutions are shown in this tutorial. If you need to work with multiple commands or depended commands and store the result temporary to do some other tasks later then you can use this feature in your script to get the output.

More info in the video:

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Linux Shell Commands

The Shell is the command interpreter on Linux systems. This document intoduces some of the basic features of the Shell and lists many of the commands or programs available on the Linux computers in Cardiff School of Computer Science & Informatics.

The Shell

The Linux command interpreter or shell is the program users interact with in a terminal emulation window. The terminal emulation window can be one in the workstation’s Graphical User Interface mate-terminal on Linux. Alternatively, it can be an application such as SSH secure shell client or PuTTY on a Windows PC that’s logged into Linux over the network.

The shell used in the School of Computer Science & Informatics is bash Bourne Again Shell. There are other shells available such as the Bourne Shell, the C-Shell and the TC-Shell, and you can choose to use a different shell if you prefer. They all have similar characteristics but each has its own particular features. This document assumes you are using bash .

Bash has the following features:


    A command prompt which may be configured by the user. The default prompt is a dollar symbol preceded by «bash» and the bash program’s version number.

/bin containing the following.

/bin/countc
bash-2.05$ countc
45

516 ls -lrt
517 ps -ef
518 pdflatex myfile.tex

See the manual page on bash for more details (type man bash ).

Bash has an additional mechanism which allows you to recall and edit previous commands using the keyboard up-arrow key. If you press up-arrow, the last command re-appears on the terminal. Press up-arrow again to get earlier commands. To rerun the command, press RETURN . To amend the command before rerunning it, use the delete key to remove characters from the end or use the back-arrow key to reposition the cursor to delete or insert characters within the command.

Shell Commands

Here is a summary of some of the commands available. For more details refer to the manual page of each command. You can see these on-line by using the man command. Just type man followed by the name of the command you want to see.

Logging out

Command Description
logout log out of a Linux terminal

Note, on a Linux workstation you will need to exit the Desktop Environment instead.

Files and Directories

These commands allow you to create directories and handle files.

Command Description
cat concatenate and print data
lpr spool file for line printing
cd change current directory
lprm, cancel remove jobs from line printer queue
chgrp change file group
ls list and generate statistics for files
chmod change file mode
mkdir make a new directory
cp copy file data
more, page display file data at your terminal
Command Description
file determine file type
mv move or rename files
find find files
pwd print working directory
grep search file for regular expression
rm, rmdir remove (unlink) files or directories
head give first few lines
tail print last lines from file
just text justification program
touch update access and modification times of a file
lpq spool queue examination program

File Editors

Editors are used to create and amend files.

Command Description
emacs GNU project Emacs
xemacs emacs with mouse action
ex, edit line editor
Command Description
pico easy text editor for vdus
pluma Mate GUI text editor
gedit GNOME text editor
vi, vim standard text editor

Vi , pico and emacs are screen-based editors which run on a vdu or in a workstations terminal emulation window; pluma , gedit and xemacs are graphical user interface (GUI) based editors with cut and paste and mouse-controlled cursor positioning.

Manipulating data

The contents of files can be compared and altered with the following commands.

Command Description
awk pattern scanning and processing language
perl data manipulation language
cmp compare the contents of two files
paste merge file data
comm compare sorted data
sed stream text editor
cut cut out selected fields of each line of a file
sort sort file data
diff differential file comparator
Command Description
split split file into smaller files
expand, unexpand expand tabs to spaces, and vice versa
tr translate characters
gawk pattern scanning and processing language
uniq report repeated lines in a file
join join files on some common field
look find lines in sorted data
wc count words, lines, and characters

Compressed files

Files may be compressed to save space. Compressed files can be created and examined.

Command Description
gzip compress files
zmore file perusal filter for crt viewing of compressed text
uncompress uncompress files
Command Description
zcat cat a compressed file
gunzip uncompress gzipped files
zcmp, zdiff compare compressed files

Information

Manuals and documentation are available on-line. Go to our web site www.cs.cf.ac.uk/systems for web-based documentation. The following Shell commands give information.

Command Description
apropos locate commands by keyword lookup
man displays manual pages online
Command Description
info displays command information pages online
yelp GNOME help viewer

Status

These commands list or alter information about the system.

Command Description
ps print process status statistics
date print the date
quota -v display disk usage and limits
reset reset terminal mode
du print amount of disk usage
script keep script of terminal session
stty set terminal options
groups show group memberships
time time a command
homequota show quota and file usage
iostat report I/O statistics
tty print current terminal name
Command Description
kill send a signal to a process
uptime display system status
last show last logins of users
users print names of logged in users
lun list user names or login ID
vmstat report virtual memory statistics
netstat show network status
w show what logged in users are doing
who list logged in users
printenv display value of a shell variable

Printing

Files can be printed using shell commands, using the GUI print manager, or direct from some applications.

You must specify a printer by name. Printers are called

Printer Name Location
tl1_lw Teaching Lab 1 (C/2.04) laser printer
tl3_lw Teaching Lab 3 (C/2.08) laser printer
Printer Name Location
tl2_lw Teaching Lab 2 (C/2.05) laser printer
tl4_lw Teaching Lab 4 (C/2.10) laser printer

Most commands which can be used to print files, expect the printer name to be given following a -P argument.

Files may be sent to the printers as simple text files or they may be processed in various ways for the laser printers.

Command Description
lpr -P printer send a file to a printer
dvips -P printer postprocess TeX file into Postscript and print on laser printer
a2ps -P printer format text file in PostScript and print on laser printer

Messages between Users

The Linux systems support on-screen messages to other users and world-wide electronic mail.

Command Description
write send a message to another local user
wall send a message to all local users
Command Description
pine vdu-based mail utility
mail simple send or read mail program
thunderbird GUI mail handling tool on Linux

Networking

The School of Computer Science & Informatics is connected to the JANET Internet Protocol Service (JIPS), the UK Universities’ network.

These commands are used to send and receive files from Campus Linux hosts and from other hosts on JIPS and the Internet, that permit such connections, around the world.

Command Description
ftp file transfer program
tftp trivial file transfer program
sftp secure shell file transfer program
rcp remote file copy
scp secure shell remote file copy
wget non-interactive network downloader
Command Description
telnet make terminal connection to another host
ssh secure shell terminal or command connection
rlogin remote login to a Linux host
rsh remote shell
curl transfer data from a url
firefox web browser
google-chrome web browser

These commands work only where the remote host permits such connections.

Programming

The following programming tools and languages are available.

General
Command Description
make maintain groups of programs
size print program’s sizes
Command Description
nm print program’s name list
strip remove symbol table and relocation bits
Command Description
cb C program beautifier
gcc GNU ANSI C Compiler
Command Description
ctrace C program debugger
indent indent and format C program source
cxref generate C program cross reference
Command Description
g++ GNU C++ Compiler
Command Description
appletviewer JAVA applet viewer
javac JAVA compiler
eclipse Java integrated development environment on Linux
FORTRAN
Command Description
f95 GNU Fortran 95 compiler
Other Languages

(Not available on all systems).

Command Description
bc interactive arithmetic language processor
matlab maths package
gcl GNU Common Lisp
perl general purpose language
Command Description
python object-oriented programming language
squeak smalltalk
php web page embedded language
mathematica symbolic maths package
asp web page embedded language

Text Processing

TeX is a typesetting language used extensively in Linux and other operating systems for producing high-quality printed documents. Another set of programs based on Troff is the standard Linux text formatting family used, for example to format manual pages.

General Commands
Command Description
fmt simple text formatter
evince GNOME PostScript previewer
Command Description
acroread PDF viewer
spell check text for spelling error
aspell interactive spelling checker
Troff
Command Description
eqn mathematical preprocessor for troff
tbl prepare tables for nroff or troff
grap pic preprocessor for drawing graphs
troff text formatting and typesetting language
Command Description
nroff text formatting language
groff GNU troff interface for laserprinting
pic troff preprocessor for drawing pictures
Command Description
tex text formatting and typesetting
latex latex formatter
Command Description
pdflatex latex formatter with PDF output
xdvi dvi previewer
dvips convert a DVI file to POSTSCRIPT

Word Processing

LibreOffice is available on the School’s Linux systems and attempts compatibilty with Microsoft Office.

Command Description
libreoffice start LibreOffice applications

Database Management

MySQL and Oracle are available.

Command Description
sqlplus run the Oracle SQL interpreter
mysql run the mysql SQL interpreter
sqldeveloper Oracle SQL Developer GUI interface
mysql-workbench GUI interface for MySQL

Cardiff University is a member of the Russell Group of Universities
Cardiff University is a registered charity No. 1136855
Copyright © Cardiff University

Источник

Читайте также:  Build firefox on windows
Оцените статью