-
Notifications
You must be signed in to change notification settings - Fork 4
/
*nix Command Line and Shell (Bash) Programming
1158 lines (965 loc) · 64.6 KB
/
*nix Command Line and Shell (Bash) Programming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
*nix Command Line and Shell (Bash) Programming
These notes are for general command line usage and shell programming.
There is a separate notes document for developer tools on the command line.
-------------------- Command Line --------------------
*nix systems' file structure is always a single tree with a root (/) directory, unlike Windows file
systems that have each physical hard-drive be a different drive, therefore a different tree.
You type commands into a command line using a shell. A shell is simply the program you
use on the command line to enter commands to be run by the system. There are many different
shells in the *nix environment. The most popular Linux shell is Bash, and it is the default
shell used when you open a command line terminal. The four basic shells are:
Bash (Bourne Again Shell)
sh (Bourne Shell)
csh (C Shell)
ksh (Korn Shell)
The Shell Scripting Notes further down in this document are for Bash scripting.
Most programs are installed in the /usr/bin directory.
Most commands operate like this: command -options arguments
Command Completion:
Pressing tab once will complete a command or filename if it is the only command or filename that
starts with the letters you've already typed.
If you can't remember exactly what a certain command is, if you can at least start the command,
then just press tab twice and all commands with those starting letters will be output.
- vs -- options:
Options for a command can come in a shortened form using -option or in long form using --option.
This shorthand "-" version is usually used on the command line itself, but for shell scripting
it is better to using the long form "--" version because then it will be more clear what the
option is when the script is viewed later on.
File Names
File names that being with a period are hidden.
*nix systems have no concept of file name extensions, the programs used probably do care.
*nix systems allow spaces and special characters in file names but you should not use spaces (use
underscores instead) and you should limit the special characters to periods, dashes, and underscores.
A note on paths:
When you type in a command without specifying a path name then the system does not search the
entire computer, it only searches a list of directories it maintains where executable files are
kept. If it does not find the program in those directories, it will issue the "command not found"
error message. The list of directories is called your path and is contained in the Path Variable.
You can view the directories in your path with "echo $PATH", which outputs a colon-separated
list of the path names contains in your path.
You can add directories to your path with the command: export PATH=$PATH:the_directory
But a better way is to edit your .bash_profile or .profile file to include the above command, then
the command will be done automatically every time you log in.
Most Linux distributions encourage a practice of having a bin directory as a subdirectory of your
home directory, and putting all the programs you personally use in there. So you can create this
bin directory in your home directory, then add that directory to your path in the .bash_profile
file. Now any shell scripts you put in there will be executed just by typing in the name of the
program at the command prompt, no matter what directory you are in.
When a command is entered, the built-in commands are checked first to find a match, if
no match if found in the built-in commands then the PATH environment variable is checked
for the command. If the command isn't found there then the command canonot be executed
on the machine.
File System
/ root directory
/boot in linux the linux kernel and boot loader files are kept here, kernel is vmlinuz
/etc contains configuration files for the system, all file in here are text files.
/etc/passwd - contains essential information for each user, this is where users
are defined. User information is shown in the following columns:
username, password (encyrpted, displayed as just an "x"), UserID,
GroupID, GECOS (usually the person's full name or a description of
what the account is for), home folder location, and the shell.
/etc/group - contains essential information for each group on the system, this is
where groups are defined. Group information is shown in the following
columns: name of group, group password (encrypted, displayed as just
an "x"), GroupID, extra member of the group (separated by commas).
/etc/shadow - this is where the encrypted passwords for all users are held. They
used to be shown in /etc/passwd, but now they are in this file for
more security (this file isn't even accessible to normal users, only
to the root).
/etc/fstab - contains a table of devices that get mounted when your system boots
and defines the disk drives.
/etc/hosts - lists the network host names and IP addresses that are intrinsically
known to the system.
/etc/init.d - contains the scripts that start various system services typically
at boot time.
/bin, /usr/bin these two directories contain most of the programs for the system.
The /bin directory has the essential programs the system requires to
operate. The /usr/bin directory contains applications for the
system's users.
/sbin, /usr/sbin the sbin directories contain programs for system administration,
mostly for use by the superuser.
/usr contains a variety of things that support user applications.
/usr/share/x11 - supports files for the X windows system.
/usr/share/dict - dictionaries for the spelling checker (commands: look and aspell).
/usr/share/doc - various documentation files in a variety of formats.
/usr/share/man - the man pages are kept here
/usr/src - source code files. If you installed the kernel source code package, you
will find the entire linux kernel source code here (in linux machines).
/usr/local this directory and its sub-directories are used for the installation of
software and other files for use on the local machine. So software that
is not part of the official distribution usually goes here (as opposed to
/usr/bin). When you install programs on the system they should be installed
in one of the /usr/local directories, usually the /usr/local/bin directory.
/var contains files that change as the system is running
/var/log - contains log files, these are updated as the system runs. You can view
the files in here from time to time to monitor the health of the system.
/var/spool - holds files that are queued for some process, such as mail messages
or print jobs.
/lib the shared libraries (similar to DLLs in Microsoft Windows).
/home this is where users keep their personal work. In general this is the only place
users are allowed to write files.
/root this is the superuser's home directory.
/tmp a directory in which programs can write their temporary files
/dev a special directory because it doesn't contain files in the usual sense. It contains
devices that are available to the system. On *nix systems devices are treating like
files. You can read and write devices as though they were files.
/proc this directory is also special in that it does not contain files, in fact it doesn't
really exist at all, the entire directory is virtual. It contains little peep holes
into the kernel itself. There are a group of numbered entries in this directory
that correspond to all the processes running on the system. (I don't think this is
on Macs, or it is named differently).
/media, /mnt the /media directory is normal directory used in a special way, it is used
for mount points. The process of attaching a device to the directory tree
is called mounting. For a device to be available it must first be
mounted. And on systems that require manual mounting of removable devices,
the /mnt directory provides a convenient place for mounting these
temporary devices.
Wildcards
Wildcards can be used when specifying filenames, they allow you to select filenames based on
patterns of characters so that you can rapidly select groups of filenames instead of typing
out every single separate file you want to do something with. You can use wildcards with any
command that accepts filename arguments.
* matches any characters, i.e. *.html refers to all html files in a directory
? matches any single character
[characters] matches any character that is a member of the set of characters. The set of
characters can also be expressed as a POSIX character class as one of the
following:
[:alnum:] alphanumeric characters
[:alpha:] alphabetic characters
[:digit:] numerals
[:upper:] uppercase alphabetic characters
[:lower:] lowercase alphbetic characters
[!characters] matches any character that is not a member of the set of characters
Some examples of using wildcards:
* all filenames
g* all filenames the begin with a "g"
b*.txt all filenames that beging with a "g" and end with ".txt"
Data??? any filenames that beings with the characters "Data" followed by exactly three
more characters
[abc]* any filename that begins with an "a", "b", or "c"
[[:upper:]]* any filename that beings with an uppercase letter
BACKUP.[[:digit:]][[:digit:]] any filename that begins with the characters "BACKUP"
followed by exactly two numerals
*[![:lower:]] any file name that doesn not end with a lowercase letter
Commands
Commands can be one of 4 different kinds:
1. An executable program
like all those file in /usr/bin. Within this category, programs
can be compiles binaries such as programs written in C and C++ or programs written
in scripting languages such as the shell, Perl, Python, etc.
2. A command built into the shell itself
Bash provides a number of commands internally called shell builtins. The cd command,
for example, is a shell builtin.
3. A shell function
These are miniature shell scripts incorporated into the environment.
4. An alias
Commands that you can define yourself, built from other commands.
Text Editors
In Unix-like systems there are several text editors that are generally used. Nano or pico is simple
text editor that is good if you don't want to have to learn a bunch of stuff to use the text editor.
Vi or Vim (Vi iMproved) is a popular choice that comes installed in all versions of Unix-like systems
and it has tons of keyboard shortcuts to help editing go faster. However Vi or Vim is very hard for
beginners and you have to read up on it before you even try to start using it. Sames goes for Emacs,
which is the other really popular and powerful text editor on *nix systems.
To start editing or create a file using one of these text editors just type the name of the text
editor followed by the name of the file you want to edit or create.
Changing the command line prompt
Can change the command line prompt in Bash by changing the PS1 variable.
i.e. PS1="new_prompt"
Just type that into the command line and press enter.
You can see what the current value of the prompt is by typing: echo $PS1
SuperUser (the Root)
The SuperUser for a system, called the Root, is a user who can do anything on the system. The
Root cannot be locked out of any files or directories. The Root has ultimate control of the
system. The Root's home directory is /root. A normal user can switch to being the Root with
the command "su", but you have to know the Root's password. The "sudo" command is used instead
of "su" usually because it is safer than "su". The sudo command only lets a user run a single
command as root at a time, and the System Admins can restrict what root-only commands are
allowed for certain people. Only System Admins should have Root access. No normal user should
have Root access because the Root can do anything and therefore a user with access could
destroy important data or cripple the system.
The Root always has a UID of 0. You can effectively duplicate the root account just by setting
the UID of any other account to 0 in /etc/passwd - this is a way to hack the system.
Some Unix systems have a special group called wheel, only group members of wheel may use 'su'
to Root and use the Root capabilities.
----COMMANDS----
whoami
Outputs the name of the current user.
who
Shows a list of everyone that is currently on the system (along with some other information).
Syntax: who
hostname
Outputs the name of the system you are using.
pwd
Print working directory.
ls
List file and directories in the current directory.
You can list the contents of multiple directories at once
ls -l <- list the files in the working directory in long format
ls pathname pathname <- list contents of multiple directories
ls -a <- list all files (including hidden files)
ls -la <- list all files in long format
ls -F <- identifies directories from files by ending directory names with a "/"
Long format shows the file permissions, the owner, the group, the size in bytes,
modification time, and file name.
When a file's first character in its file perissions is "l" it means that the file is a
symbolic link. Also the filename will show the file (symbolic link) points ("->") to another
file (the file that is run by the symbolic link).
ls -l:
The ls -l command displays 9 columns of information: the permissions, number of links,
owner of the file, what group the file belongs to, sizes in bytes, month file was created,
day file was created, time file was created, name of the file.
The different possible file types that are displayed by the first character in the
permissions column are as follow:
- plain file
d directory
l link
p pipe
b block device // device files that read info in blocks
c character device // device files that read info in a stream
cd
Change the current directory.
Syntax: cd pathname
cd, cd ~, cd ~userName <- these change the working directory to the home directory
cd - <- this changes the working directory to the previous one
The pathname can be an absolute or relative pathname.
pushd
Changes the working directory, saving the current directory to a directory stack so that
you can return to it using the popd command.
This is what you use instead of cd if you just need to go to another directory to do
something then you want to come back to your current directory.
Syntax: pushd directoryPath
popd
Changes the working directory back to whatever directory was last pushed to the stack
using pushd.
Syntax: popd
touch
Creates an empty file
Syntax: touch filename
more
View text files starting from the top of the file. Supports paging which means if the
text is larger than the console window you can press a button to move up or down in the
output document. Press "q" to leave the contents that less has displayed and get back to
the cursor on the command line. Similar to "less" as shown below, but less is more
popular to use because it has more functions.
Syntax: more file_name
less
View text files starting from the top of the file. Supports paging which means if the
text is larger than the console window you can press a button to move up or down in the
output document. Can also use the arrow keys to move by line up and down in the document.
Press "q" to leave the contents that less has displayed and get back to the cursor on
the command line.
Syntax: less file_name
Controlling less:
Spacebar to scroll down by one full page
"b" to scroll up by one full page
Enter to scroll down by one line
"q" to exit less
"G" to go to end of the text file
"1G" to go to beginning of the text file
"/characters" to search for sequence of characters from current point to end of file
"n" to repeat the previous search
"h" to display a complete list of less commands and options
file
Classify a files contents. Tells you what kind of data a file contains.
Syntax: file filename
Output of a python file for instance will be:
filename: a path script text executable
Some file types are:
ASCII text
Bourne-Again shell script text
HTML document text
Zip arhive data
JPEG image data
GNU tar archive
etc.
ln
Creates a link to another file.
There are two kinds of links, hard and soft (or symbolic).
The ln command takes two arguments, first argument is the file to link to, second argument
is the name of the new file being linked to the original file.
Symbolic links are useful for say a file that the system uses but the system expects it to
always have the same filename but say there are different versions of whatever thing it is,
and the symbolic link will make it so even if the version changes it will always have the same
filename that the system can use, which points to the correct version. This would be done by
just updating what file the link points to if a new version is to be used. To make a symbolic
link you just include the -s option.
Syntax for symbolic link: ln -s file1 file2
Hard links make an exact clone of the file, rather than just pointing to a file somewhere else
on the system.
Syntax for hard link: ln file1 file2
Differences between hard and symbolic links are as follows. Hard link won't show the "l"
when you use ls -l, because it doesn't know it's a link. A hard link won't take up any
disk space. Hard disk can't span filesystems (can't be used across partitions). A symbolic
link does show the "l" identifier when displayed with ls -l, a symbolic link does take up
space (albeit very little space since it is just a link to a file), and a symbolic link
can be used in other partitions on the system.
cat
Outputs contents of a file to the command line. "cat" stands for concatenate. Can output
one or more files to the console window by listing one or more arguments.
cp
Copies files and directories.
Can be used to copy a file in the same directory, or to copy files to other directories.
Syntax:
cp file1 file2 copies file1 to a new filename (file2).
cp file ... directory copies multiple files (and/or directories) to a
different directory.
Examples of using cp:
cp file1 file2 copies contents of file1 into file2, if file2 does
not exist, it is created.
cp -i file1 file2 same as above except the -i (interactive) option means
that if file2 already exists, the user is prompted
before it is overwritten with the contents of file1.
cp file1 dir1 copies the contents of file1 into a file named file1
inside of directory dir1.
cp -R dir1 dir2 copies the contents of directory dir1, if dir2 does
not exsit then it is created. Otherwise it creates a
directory named dir1 within dir2.
mv
Moves or renames files and directories depending on how it is used.
The reason it can move or rename files is because you need to think about it as renaming
an entire path, not just the filename. So you can rename the path in a way to move the file
to a different directory while keeping the same file name, oryou can rename the path by
keep everything the same except the last part of the path (the filename) which will just
rename the file and not move it.
When moving you don't have to put directory/filename if you aren't changing the filename,
Unix knows what is a directory and what isn't so if your second argument is just a path to
a directory it will just move the file there and keep the same filename.
Syntax to rename a file: mv filename1 filename2
Syntax to move files/directories to a different directory: mv file ... directory
Examples of using mv:
mv file1 file2 if file2 does not exist then file1 is renamed file2,
if file2 does exist then its contents are replaced
with the contents of file1.
mv -i file1 file2 same as above except the -i option means that if file2
exists then the user will be prompted before it is
overwritten with the contents of file1.
mv file1 file2 file3 dir1 file1,file2,and file3 are moved to directory dir1, if
dir1 does not exists mv will exit with an error.
mv dir1 dir2 if dir2 does not exist then dir1 is renamed dir2,
otherwise the directory dir1 is moved within dir2.
rm
Removes (deletes) files and directories.
To delete directories you have to use the -r option, which stands for recursive and will
recursively delete all files and sub-directories within the specified directory. If the
directory is empty though you don't need to use the -r option.
Syntax to delete a file: rm file ...
Syntax to delete a directory: rm -r directory
Examples of using rm:
rm file1 file2 deletes file1 and file2.
rm -i file1 file2 the -i (interactive) option gives the user a prompt
before each filed is deleted
rm -r dir1 dir2 directories dir1 and dir2 are deleted along with all
their contents
rm *~ delete all files in the current working directory that
end with the "~" character. Some applications create
backup files using this naming scheme, using this
command will clean them out of a directory.
Tip for using rm: You can do massive damage to the system by deleting stuff on accident,
especially when using wildcards. One way to safeguard yourself is to construct the command
with ls before you use rm, this way you can see all the things listed that will be deleted
with the command.
mkdir
Creates one or more directories.
Syntax: mkdir directory ...
Using the -p option and specifying a whole path will make directories in the path that
don't exist yet.
type
Displays information about command type.
A shell builtin command that displays the kind of command the shell will execute, given
a particular command name.
Syntax:
type command
Examples of using type:
type type output: type is a shell builtin
type ls output: ls is aliased to ls --color=tty
type cp output: cp is /bin/cp
which
Locates a command.
Syntax:
which command
Example of using which:
which ls output: /bin/ls
help
Displays reference page for shell builtin commands.
The help command is bash's built-in help facility that is available for each of the shell
builtins. You can add the -m option to change the format of the output (I think -m doesn't
work on Macs).
In the description of a command, when it shows syntax for a command, square brackets refer
to optional items, and a vertical bar "|" indicuates mutually exclusive items.
Many executable programs support a "--help" joption that displays a description of the
command's supported syntax and options (This maybe doesn't work on Macs, but when you type
incorrect options for a command it will print out an error message and then that command's
usage syntax, so that works basically the same way).
man
Displays an on-line command reference.
Most executable program intended for command line use provide a formal documentation called
a manual or man page. On most systems the "man" command uses the "less" program to display
the man page.
Syntax: man program <- program is the name of the command
Other documentation:
Many software packages installed on a system have documentation files residing in the
/usr/share/doc directory. Most of them are stored in plain text, some in html. If the
files have a .gz file extension that means they have been compressed with the gzip
compression program. The gzip package includes a special version of less called zless
that will display the contents of gzip-compressed text files.
df
View the partitions on the system. "df" stands for "disk filesystems".
Partitions slice up the harddrive into pieces.
Using the -h option specifies "human readable" format, which will display sizes in megabytes
or gigabytes instead of kilobytes.
Syntax: df -h
groups
Outputs what groups the current user belongs to.
cal
Displays a calendar in the console window.
apropos
Used to find commands when you aren't sure of the spelling.
Takes a word as an argument and will output all available commands related to that word or
with that word in their spelling. Also outputs a short description of what each command does.
Syntax: apropos word
grep
Used to search for a particular string in a file and output all instances it finds to the
console window. Searches standard input if no files are given as arguments.
"grep" stands for Global Regular Expression Print.
Syntax: grep string file
wc
Outputs newline, word, and byte counts for each file listed.
Syntax: wc file
Result: lineCount wordCount charCount filename
Result ex: 5 28 107 filename
Various options to just print out a single count.
-c prints byte count
-m prints character count
-l prints line count
-w prints word count
find
Search for files in a directory hierarchy (including the specified directory and all its
subdirectories).
Can search by name or type of item in the directory. Probably in some other ways too, not sure.
Syntax: find directory searchType searchItem options
Example: find . -name "*.txt"
Result: Will display all files in the working directory that end in .txt
Example: find /home -type -f | wc -l
Result: Will output the number of files in the /home directory and all its
sub-directories.
export
Change value of environment variables.
Syntax: export envVar="new value"
Note that you don't include the $ before the envVar when using this command.
unset
Remove an environment variable from the environment.
Sytnax: unset envVar
xargs
Build and execute command lines from standard input.
NEED TO READ ABOUT THIS.
passwd
Allows a user to change their password.
Syntax: passwd
I/O Redirection
Most command line programs that display their results do so by sending them to standard
output, which displays on screen, but you can redirect standard output to a file using
the ">" character to overwrite the file, or ">>" to append to the file. If the file
doesn't exist it will be created.
>
Redirects stdout to a file, overwrites the file.
Syntax: command > filename
i.e. ls > myfile.txt
>>
Redirects stdout to a file, appends to the file.
Syntax: command >> filename
i.e. ls >> myfile.txt
To redirect standard input from a file instead of from the keyboard use the "<" character.
<
Redirects stdin from a file.
Syntax: command < myfile.txt
i.e. sort < myfile.txt
sort < filelist.txt > sorted_filelist.txt
In the last example, sort takes the contents of filelist.txt as its arguments by
redirecting stdin to come from that file, and then it redirects stdout to print to
the second file instead of printing to the screen. The order of the redirection does
not matter, but the redirection operators must appear after any other options and
arguments in the commnand.
File Descriptors
Unix-like systems can support up to 10 file descriptors, numbered 0 to 9. But generally you
just use the first three:
Standard Input STDIN 0
Standard Output STDOUT 1
Standard Error STDERR 2
When you use a redirect like > there is an implied 1 there like so: 1>.
Since > has an implied file descriptor of 1 (STDOUT), in order to redirect STDERR you need
to make it explicit that you want to redirect it by putting in the file descriptor 2, like so:
command argument 2> filename
In the above syntax example if the command causes an error it will redirect the error message
to the specified file.
Anytime a file receives more information (from adding text to a file, reading command line
arguments, or having information piped to a command) STDIN is used.
Any command that can take a file as an argument can also take its input by STDIN. This is
because all information received by a file/command is STDIN; if a command takes a file as an
argument then that file is sent to the command as STDIN, so instead of using a file you can
just use straight up STDIN, like echo or cat something into the command by piping it in. Piping
something takes STDOUT from the left operand of the pipe and sends it through STDIN to the
right operand of the pipe.
i.e. wc file // this works
echo "yo man" | wc // this works too
cat file | wc // so does this
Combining File Descriptors:
Would do this if you wanted to save boththe input and output to a file.
i.e. cat file.txt > file2.txt 2>&1 // combine STDERR and STDOUT
As shown in the example above you put the combined file redirect at the end of the
command and use a & on the final one I guess. This takes the output of file.txt, redirects
it into file2.txt, but the 2>&1 means that all STDERR will be redirected to STDOUT as well.
So if any errors pop up they will be saved to the file. So if there are no errors with
"cat file.txt" then that file will be saved to file2.txt, but if there are errors then the
error message(s) will be saved to file2.txt.
Note that using 'cat' as shown in the above example is known as a Useless Use of Cat
because using the redirct > will automatically take the contents of file.txt as STDOUT
and put them in file2.txt as STDIN, so no need for a cat.
Disabling all Output:
Sometimes when you run a command you don't want to see any output (no STDERR or STDOUT).
To do this you can redirect everything to a special device known as /dev/null.
Syntax: file.txt > /dev/null 2>&1
/dev/null is like a black hole, anything that goes into it vanishes from the system.
Pipelines
The most useful and powerful thing you can do with I/O redirection is to connect multiple
commands together with pipelines, a pipeline is the "|" pipe bar character. With pipelines
the standard output of one command is fed into the standard input of another.
|
Connects multiple commands together so the standard output of a command is fed as
standard input into the next command.
Syntax: command | command | command
i.e. ls -l | less // this lets any command have scrolling
// output using the less program.
ls -lt | head // displays the 10 newest files in the
// current directory.
du | sort -nr // displays a list of directories and how
// much space they consume, sorted from
// largest to smallest
find . -type f -print | wc -l // displays the total number of files in
// the current working directory and all
// of its subdirectories
ls -l | grep b // will take the output of "ls -l" and send
// it to "grep b" which will only output
// lines from the "ls -l" output that contain
// the letter "b"
Filters
Filters are a kind of program frequently used in pipelines. Filters take standard input
and perform an operation upon it and send the results to standard output. The can be
combined to process information in powerful ways. Some common programs that can act as
filters:
sort Sorts lines of a text file then outputs the result on stdout.
uniq Given a sorted stream of data from stdin, it removes duplicate lines of data.
grep Examines each line of data it receives from stdin and outputs every line that
contains a specified pattern of characters. Basically a search.
fmt Reads text from stdin, then outputs formatted text (neat paragraphs) to stdout.
pr Takes text input from stdin and splits the data into pages with page breaks,
headers, and footers in preparation for printing.
head Outputs the first few lines of its input. Useful for getting the header of a file.
tail Outputs the last few lines of its input. Useful for things like getting the most
recent entries from a log file.
tr Translates characters. Can be used to perform tasks such as upper/lowercase
conversions or changing line termination characters from one type to another (for
example, converting DOS text files into Unix style text files).
sed Stream editor. Can perform more sophisticated text translations than tr.
awk An entire programming langauge designed for constructing filters. Extremely powerful.
lpr Accepts stdin and sends it to the printer.
i.e.
cat text.txt | fmt | pr | lpr // Formats, paginates and prints text.txt
cat unsorted.txt | sort | uniq | pr | lpr // Sorts, removes duplicates,
// paginates, and prints unsorted.txt
tar A gzipped tar file is a traditional Unix style tape archive file (created with tar)
that has been compressed with gzip, it will have file extnesions like ".tar.gz" or
".tgz". Use the tar command in this example to iew the directory of such a file on
a Linux system.
i.e. tar tzvf file.tar.gz | less
Expansion
Expansion is the process of the shell performing several processes upon the text before it carries
out the command, like for instance using the * wildcard. Expansion is when you type something and
it is expanded into something else before the shell acts upon it.
An example:
The "echo" command outputs whatever is sent as an argument to it. So "echo my name is todd" outputs
"my name is todd" to the terminal. But for "echo *" the shell expands the * character to the names
of all the files in the current working directory, so echo never sees a "*", it only sees the
expanded content. Likewise "echo c*" would list all the files/directories in the current working
directory that start with "c".
echo *s <-- would print out all files/directories in current directory ending with an "s".
Pathname Expansion is the mechanism by which wildcards work.
Tilde Expansion is when you use a tile "~" to refer to (and gets expanded to) the name of the
home directory.
i.e. echo ~tkrone * // this outputs all directories/files in my home directory
Arithmetic Expansion is how the shell allows arithmetic to be performed on the shell prompt, in the
form $((expression)).
i.e. echo $((3+4)) // this outputs: 7
Arithmetic expansion only supports integers. Its operators are: + - * / % **
Brace Expansion is a way to create multiple text strings from a pattern containing braces. Patterns
to be brace expanded may contains a leading portion called a preamble and a trailing portion called
a postscript. The brace expansion itself may contain either a comma-separated list of strings, or
a range of integers or single characters, but it can't contain any embedded whitespace. When using
echo for a brace expansion each string will be separated by a space.
Note in the examples, ".." is used to set a range (inclusive). Notice in the last example you can
also nest brace expansions.
i.e.
echo Preamble-{A,B,C}-Postscript
// outputs: Preamble-A-Postscript Preamble-B-Postscript Preamble-C-Postscript
echo Number_{1..3}
// outputs: Number_1 Number_2 Number_3
echo {Z..T}
// outputs: Z Y X W V U T
echo a{A{1,2},B{3,4}}b
// outputs: aA1b aA2b aB3b aB4b
The most common application of brace expansions is to make lists of files or directories to be
created. For example, if you wanted to make a directory of photos split up into sub-directories by
month and year you could do something like this:
mkdir 0{1..9}/{2010..2013} {10..12}/{2010..2013}
Parameter Expansion is basically the use of variables. So it is much more useful in shell scripts
than just straight up on the Command Line. Parameter expansion expands a variable name into
whatever value is held by the variable. To use it you just put a $ in front of a variable name.
Syntax: $varName
There are some environment variables built into the system/shell, like $USER refers to the user
name. So for me the command:
echo $USER // outputs: tkrone
The environment variable $HOSTNAME contains the hostname for the system.
To see a list of all environment variables use either of these commands:
printenv | less or env | less
If you use a variable that doesn't exist with the echo command it will just print a blank line.
Command Substitution:
Command substitution allows us to use the output of a command as an expansion.
Syntax: $(command)
So this allows you to package the output of some command as the argument for some other command.
i.e. echo $(ls) // expands the output of ls
ls -l $(which cp) // will print the long form of the /bin/cp command
You can do any command like this, for example you could do some complex command with pipes in it.
An alternate syntax for command substitution in older shell programs, which is also supported in
Bash, is to use back-quotes instead of $().
Alternate Syntax: `command` // instead of $(command)
Quoting:
Without using any quotes the echo command removes and extra whitespace and will automatically
expand anything with a $ before it into a variable, and if that variable doesn't exist it doesn't
print anything for it.
For example: echo This is a $100.00 dollar bill.
outputs: This is a 00.00 dollar bill.
The Fix: echo 'This is a $100.00 dollar bill.'
outputs: This is a $100.00 dollar bill.
The above case is true because the shell treats $1 as a variable, which doesn't exist, and so it
prints nothing for it.
Using quotes is the fix to the above mentioned problems. Using quotes will make it so any extra
whitespace is output, and it will make the shell see anything following a $ as part of a string
instead of as a variable. Note that for the variable example double-quotes will not work, only
single-quotes will fix it.
Double Quotes cause most special characters used inside the shell to lose their special meaning and
are treating as normal characters.
The exceptions are: $ \ ` <-- dollar sign, backslash, back-quote
This means word-splitting, pathname expansion, tilde expansion, and brace expansion are suppresed,
but parameter expansion, arithmetic expansion, and command substitution are still carried out.
echo $(cal) // will print out the whole calendar without any newlines because echo would
// treat each space (including newlines_) in the command substitution as
// separate arguments.
echo "$(cal)" // this will print out the calendar as the command cal normally does because
// echo only gets sent one argument, which is the output of $(cal).
Single Quotes suppress all expansions so that exactly what is written is output in an echo
statement.
Escape characters, using the backslash \, can be used when you only want to suppress a single
special character. Often this is done inside double quotes.
i.e. echo "This is \$100.00 dollars."
The above example would print the $1 instead of thinking it is a variable, due to escaping the $
with the backslash.
Escape characters can also be used to suppress the special meaning of a character in a file name.
Because it's possible to use characters in a file name that has a special meaning in the shell,
you would want to escape any such characters when typing out that file on the command line.
Such characters include "$", "!", "&", " ", etc.
The Backslash characters can also be used to make the shell ignore a newline character, by that I
mean it allows a single command to flow onto multiple lines. For this to work the newline must
occur immediately after the backslash, you can't have any spaces after the backslash. The reason
for this is because the backslash escapes whatever character immediately follows it, so if there
is a space after it then it will just escape the space instead of the following newline
character.
i.e. echo "Hey Man \
whats happening." // output: Hey Man whats happening.
To use the standard escape sequences with the echo command you need to include the option -e.
Common escape characters are: \n \t \a \\ \f
i.e. echo -e "Print an extra newline\n"
Side note: the -n option for echo gets rid of the automatic newline.
i.e. echo -n "No automatic newline at the end of this."
Permissions
Unix-like systems are different from other operating systems in that they are multi-user, meaning
that more than one person can be operating the computer at the same time, like remoting in via
ssh (secure shell).
Commands dealing with permissions are chmod, su, sudo, chown, chgrp.
On a *nix system each file and directory is assigned access rights for the owner of the file, the
members of a group of related users, and everybody else. Right can be assigned to read, write, and
execute a file. The permissions for a file/directory are shown in the long form of the ls command.
Commands:
chmod
Used to change the permissions of a file or directory.
Syntax: chmod 754 filename
There are two ways to specify the permissions, one of them is called octal notation.
Octal notation: 1 = execute, 2 = write, 4 = read
The 3 different permission sets, for owner, group, and other are each given in 3 binary
digits representing all combinations of execute, write, and read. Read, being 4, is
controlled by the third (left-most) bit. Write, being 2, is controlled by the second (middle)
bit. Execute, being 1, is controlled by the least-significant bit.
1 = 001 = execute
2 = 010 = write
3 = 011 = write,execute
4 = 100 = read
5 = 101 = read, execute
6 = 110 = read, write
7 = 111 = read, write, execute
Permissions in the ls -l command are in the following format: -rwx rwx rwx
The first "-" will show the type of item it is, "d" for directory, "l" for link, etc.
Each "r", "w", "x" will be shown if it has that permission, or a "-" will be shown wherever
it doesn't have that permission.
To use chmod you write the command, followed by the decimal number representing the permissions
for each set, and then the filename.
For directories the chmod command is used to set permissions, but the meaning of r,w,x is
different than for files.
r - allows contents of the directory to be listed if the "x" attribute is also set.
w - allows files within the directory to be created, deleted, or renamed if the "x"
attribute is also set.
x - allows a directory to be entered.
Basically the options for directories each set of users is basically:
5 = r-x can enter directory and list the files
7 = rwx no restrictions on the directory
0 = --- no access to the directory
chmod Examles:
chmod u+wx filename
chmod 755 filename
chmod g-x filename
chmod o+rwx filename
chmod u+x, g-x, o-wx filename
chmod a+x filename // "a" here stands for all (i.e. ugo, i.e. user,group,owner)
su/sudo
Allows the user to temporarily become the super user (the Root), in order to perform some
important system administration tasks. You can also become any other user by sending a dash and
then a username as the argument to 'su', however to do this you must first be the superuser/Root.
su stands for substitute user.
Putting a dash '-' after 'su' means you'll inherit all of Root's specific environment
variables (including the Path), but with no dash you just keep your own variables.
When using the su command you will be prompted for the super user's password.
After executing the su command a new shell session will start as the super user. To exit
as super user type "exit" in the command shell.
Syntax for su: su // then enter the superuser's password
su - // become superuser and inherit superuser's env variables
su - username // become another user (when you are already the superuser)
In some distributions, like Linux, you use the sudo command instead of the su command.
With sudo, one or more users are granted superuser priviledges on an as needed basis. To
execute a command as superuser, the desired command is simply preceeded with the sudo
command. After the command is entered, the user is prompted for the user's password rather
than the superusers password.
The key difference between sudo and su is that using sudo never starts a new shell as the
superuser, it merely executes a single command as the superuser, therefore the user is
less likely to screw stuff up as the superuser and so sudo is a safer command.
Syntax for sudo: sudo command // then enter user's password
chown
Changes the owner of a file or directory.
Most be the superuser to change ownership of a file.
Syntax (using sudo): sudo chown newOwner filename
The chown command works the same way on directories as it does on files.
chgrp
Changes the group ownership of a file or directory.
Don't need to be superuser to change group ownership, but you must be the owner of the
file or directory to change its group ownership.
Syntax: chgrp newGroup filename
Job control
*nix systems are also multi-tasking, and you can manipulate the multi-tasking element of the
operating system with the command line interface.
Multi-tasking is achieved by switching what processes are being executed at intervals so that it
appears that several tasks are being performed at once.
The commands that are used to control processes are: ps, kill, jobs, bg, fg
ps list the processes running on the system
kill send a signal to one or more processes to kill it
jobs an alternate way of listing your own processes
bg put a process in the background
fg put a process in the foreground
top displays in real time the system stats associated with each process
Daemons
Daemons are programs that run on the system on their own. They do a single job and just wait
on the system until something requires them to do their job, and then they do it.
Running a program in the background:
You can open up graphical programs from the CLI, however, if you do then you can't use the
command prompt until the program that was started closes, at which point you can access the
command prompt again.
In order to open a graphical program but not lose use of the command prompt you can either
put "&" after the command to open the program: command &
or if you forget to put the "&" when opening the program on the CLI, you can press Ctrl-z when
the terminal has focus and this will suspend the process - it still exists but is idle - at
which point you have access to the command prompt, and simply by typing the "bg" command you
can then move that process to the background.
So do either: command &
or: command
[press Ctrl-z]
bg
To put the process back in the foreground (and thus giving the command prompt back over to it)
just type the fg command into the command prompt.
Listing the processes:
jobs
Use the jobs command to list all processes running in the background.
ps
Use the ps command to list all processes.
The ps command by itself only lists processes launched from the current terminal. Use
the -x option to list all processes, even those not launched from the current terminal.
-a option shows all processes running for all users
-x option shows even processes run by the system (daemons)
-u option shows the user who is running the process
Syntax: ps -aux
Some columns show in the ps output are the ProcessID (PID), TT which jdisplays a location
for your terminal, STAT which stands for "state" and gives the current state of the process,
TIME is how much processing time the system has used on the process, and COMMAND is the command
that it is.
top
Shows a bunch of real-time (as in it updates itself on the screen) stats associated with
all the processes running on the system.
Killing a process:
You can terminate a process (if it for example becomes unresponsive) using the kill command.
For background processes, use the jobs command to find the job number of the process, which is
shown between square brackets, or the process ID, which is shown after the job number. Or
use the ps command to find the process ID (PID) for the process. Use the kill command in the
following way:
kill PID i.e. kill 25923
or kill %jobNumber i.e. kill %1
While the kill command is used to terminate processes, its real purpose is to send signals to
processes. Most of the time the signal is to tell the process to go away, but if can be used
for other signals. Programs that are properly written listen for signals from the OS and respond
to them, most often to allow some graceful method of terminating. For example, a text editor
may listen for signals that indicate the user is logging off or the computer is shutting down.
When it receives such a signal it save the work in progress before exiting. The kill command
is used to send different signals to processes.
Typing "kill -l" will give a list of all the signals the kill command supports.
Use the different kill signals like so,
Syntax:kill -signal // -signal can be the signal name or number (list in kill -l)
i.e. kill -SIGKILL PID or kill -9 PID
Some useful signals are:
Signal 1: SIGHUP
Hang up signal. Programs can listen for this signal and act upon it. This signal is
sent to processes running in a terminal when you close the terminal.
Signal 2: SIGINT
Interrupt signal. This signal is given to processes to interrupt them. Programs can
process this signal and act upon it. You can also issue this signal directly by typing
Ctrl-C in the terminal window where the program is running.
Signal 15: SIGTERM
Termination signal. This signal is given to processes to terminate them. Programs can
process this signal and act upon it. This is the default signal sent by the kill
command when no signal is specified.
Signal 9: SIGKILL
Kill signal. This signal causes the immediate termination of the process by the kernel.
Program cannot listen for this signal, it just automatically kills the process.
For example, if there is a program that is hopelessly hung up and you want to kill it. First,
use the ps command to get the PID for that process ("ps -x | grep processName"), use the
command in the parenthesis to output only the process you are looking for. Then, use the
SIGTERM, the default kill command, to try to kill the process ("kill -SIGTERM PID" or just
"kill PID"), where "PID" is the processes PID. If the process doesn't terminate (it is
ignoring the signal) then send a harsher kill signal like SIGKILL ("kill -SIGKILL PID").
-------------------- Shell Programming --------------------