Category: Linux & Open Source

Linux administration on Ubuntu and CentOS: commands, scripting, networking, services (DNS, DHCP, Samba, NFS, Apache, Squid) and LPIC study notes.

  • 5 UNIX / Linux file Command Examples

    What is file?

    The file command accepts a file as an argument and performs certain tests to determine the correct file type. For example text, executable etc.

    5 file Examples

    1. A basic example

    The following basic example determines the file type for all the files present in current directory.

    $ file *
    cmd:          ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xfac3f75dfae01e0ac037c39099182eb5c51fca82, not stripped
    cmd.c:        ASCII English text
    file:         ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xcd78d8859677bf20f34fa16142593494b01cd1ee, not stripped
    file.c:       ASCII C program text
    helloworld.c: ASCII text
    helloworld.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
    input.txt:    ASCII text
    split:        directory

    2. Change the delimiter using -F option

    As can be seen in the above example, the default delimiter between file name and file type is ‘:’. This can be changed using -F option.

    Here is an example :

    $ file -F - *
    cmd-          ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xfac3f75dfae01e0ac037c39099182eb5c51fca82, not stripped
    cmd.c-        ASCII English text
    file-         ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xcd78d8859677bf20f34fa16142593494b01cd1ee, not stripped
    file.c-       ASCII C program text
    helloworld.c- ASCII text
    helloworld.o- ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
    input.txt-    ASCII text
    split-        directory

    3. Determine the file type of stdin using – option

    To determine the file type of stdin file, use the ‘-‘ option.

    Here is an example :

    $ file  -
    Hello World
    /dev/stdin: ASCII text

    4. Represent file type in form of mime-type using -i option

    By default, the information related to file type is presented in form of human readable string. This can be changed to mime-type string using -i option.

    Here is an example:

    $ file -i *
    cmd:          application/x-executable; charset=binary
    cmd.c:        text/plain; charset=us-ascii
    file:         application/x-executable; charset=binary
    file.c:       text/x-c; charset=us-ascii
    helloworld.c: text/plain; charset=us-ascii
    helloworld.o: application/x-object; charset=binary
    input.txt:    text/plain; charset=us-ascii
    split:        inode/directory; charset=binary

    5. Change alignment of output using -N option

    The alignment of the output can be changed in way that there is no padding after file name by using -N option.

    Here is an example :

    $ file -N *
    cmd: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xfac3f75dfae01e0ac037c39099182eb5c51fca82, not stripped
    cmd.c: ASCII English text
    file: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0xcd78d8859677bf20f34fa16142593494b01cd1ee, not stripped
    file.c: ASCII C program text
    helloworld.c: ASCII text
    helloworld.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
    input.txt: ASCII text
    split: directory

    Syntax and Options

         file [-bchiklLNnprsvz0] [--apple] [--mime-encoding] [--mime-type]
              [-e testname] [-F separator] [-f namefile] [-m magicfiles] file ...
         file -C [-m magicfiles]
         file [--help]
    Short Option Long Option Option Description
    -b –brief Do not prepend filenames to output lines (brief mode).
    -C –compile Write a magic.mgc output file that contains a pre-parsed version of the magic file or directory.
    -c –checking-printout Cause a checking printout of the parsed form of the magic file. This is usually used in conjunction with the -m flag to debug a new magic file before installing it.
    -e –exclude Exclude the test named in testname from the list of tests made to determine the file type
    -F –separator Use the specified string as the separator between the filename and the file result returned. Defaults to ‘:’.
    -h –no-dereference option causes symlinks not to be followed (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is not defined.
    -i –mime Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say ‘text/plain; charset=us-ascii’ rather than “ASCII text”.
    -k –keep-going Don’t stop at the first match, keep going. Subsequent matches will be have the string ‘12- ’ prepended. (If you want a new-line, see the -r option.)
  • 5 Practical Examples To Delete / Remove Directory in Linux ( rmdir )

    Question: How can I delete empty directory, directory with files and sub directories in Linux / Unix ? Also, how can I use an alias effectively for rm and rmdir command?
     
    Answer: You can delete empty directory using rmdir command, or directory with content using rm command. Deletion can be done interactively, recursively, forcefully, or through alias. In this article, let us review 5 practical examples that shows how to delete the directories in Linux like systems.

    1. How to Delete Empty Directories in Unix?

    rmdir command will delete the empty directories. i.e directory without any sub-directories or files.

    rmdir DIRNAME

     
    To ensure that you are deleting an empty directory you should use rmdir command. If there is any
    files / directories in that directory it will display the following error.

    $ rmdir test
    rmdir: failed to remove `test': Directory not empty
    

    2. How to Delete Nested Empty Directories in Linux?

    Use option -p, to delete nested directories as shown below.

    $ rmdir -p dir1/dir2/dir3

     
    Note: Don’t get panic that how a directory can be nested and also empty. It is nested when you are invoking the command, but it deletes the inner most directory first, and makes the next level directory empty then it deletes that directory. And it continue doing so.

     
    The rmdir -p dir1/dir2/dir3 is equivalent to

    $ rmdir dir1/dir2/dir3 dir1/dir2 dir1
    

    3. Delete Directory Which has Content (i.e Directory with Files and Sub-directories)

    Some times you may want to delete directory which has contents in it. You can do it with rm command as shown below.

    $ rm -rf DIRNAME

     
    This will delete the directory including all the files and sub-directories. This is very dangerous when you use it accidentally as you cannot recover those files easily. So it is strongly recommended that you pay attention and think twice before executing the rm -rf command.

    4. Delete Interactively: Avoid using -f in rm at the early stages.

    If you’ve ever accidentally executed rm -rf by mistake, you may want to seriously consider using -i option to delete the files and folders interactively as shown below (especially under root).

    Deleting a directory recursively & interactively.

    # rm -ir DIRNAME

    Deleting a file interactively.

    # rm -i FILENAME

    If you are a Linux newbie, don’t use -f option in root until get super comfortable with the command line. Instead, try to use -i option as shown above.

    5. Useful rm and rmdir Aliases

    You can make the interactive rm option as your default rm command using alias as shown below.

    Alias to make rm interactive

    # alias rm="rm -i"

    While using the rm command, it will be always execute rm -i and ask for confirmation before deleting any files. But be careful that when you give -f option then you wont get the interactive prompt even if you have the -i option in it.

     
    For example, in the following command -i don’t have any effect.

    $ rm -irf DIRNAME

     
    In this case, the above command (with the rm alias) is equivalent to the following command.

    $ rm -rf DIRNAME

     
    All the following rm options are valid and does the same functionality. i.e recursive and forceful delete.

    • rm -fr
    • rm -rf
    • rm -r -f
    • rm -f -r

    Alias to make rm verbose

    If you want rm or rmdir to print what it is doing then you can use the traditional verbose option.

    alias rm="rm -v"
    alias rmdir="rmdir -v"
    

     
    Note: Make this setting permanent by adding alias command to either ~/.bash_profile (or) ~/.bashrc file.

     
    You can remove files or directories, empty or non-empty, nested or single using rm and rmdir commands. But before invoking the command think twice about deleting as it will become hard to recover a file once you’ve deleted it by mistake.

  • Linux touch command – Why do we need to change Timestamp?

    We may use touch command in Linux to create an empty file. Of course we can use another command such as vi, nano or any editing tools to do it. But you may need more steps do it. But do know it that the main function of touch command is not create an empty file?

    What is touch command

    As we know, every file has timestamp attached to it. This time stamp is access time and modification time. Touch command is a command for file access and modification time.

    Why we need touch

    Since touch command description is to change timestamp, we may wonder why do we need to change timestamp? This question also comes to our mind. But then, we think there is a reason why we need it. If you are participating in open source projects over sea, then timestamp may become important. Compiling a source code files may need a same region of timestamp. If not, the program may failed to compiled.

    Run touch without options

    To use touch command is quite simple. Just type :

    $ touch file_name

    Please take a look a screenshot below.

    Touch command

    File_1.txt originally has timestamp 12:42. After we do touch command, it changed to 17:08. By default, touch will change the file timestamp into current time.

    Change only Access time

    As we mention before that every file has Access time and Modify time attached to the file. File_1.txt above has timestamp 17:08. We can see more detail about it.

    Detail timestamp

    We see that Access time and Modify time has the same value which is 17:08:35 and the timezone is GMT +7.

    Now if we want to change only the Access time, we need to use -a option.

    $ touch -a file_1.txt

    Touch -a option

    As you see, the Access time is changed into 17:51:37 but the Change time is still 17:08:35

    Change only Modify time

    To do this, we can use -m option. Now we will use file_2.txt as an example.

    File_2.txt detail timestamp

    $ touch -m file_2.txt

    Touch -m option

    Now the Modify time is change from 12:42:20 to 17:57:20. Please note, that the Change field value willalways keep record when the file is accessed or modified.

    Change into custom timestamp

    Both -a and -m option will change the file timestamp into current time. We can also possible to change it into custom timestamp. To do this, use -t option.

    From file_2.txt above example, we knew that its time stamp are :

    • 12:42:20 for Access time
    • 17:57:20 for Modify time
    • 2014-01-14 for the date

    Let say we want to change it into 09:58:27 for both Access time and Modify time and 12 January 2014. To do this, we can use this command :

    $ touch -t 201401120958.27 file_2.txt

    Touch using -t option

    -t option is consist of :

    [[CC]YY]MMDDhhmm [.SS]

    • CC – The first two digits of the year
    • YY – The second two digits of the year
    • MM – The month of the year [01-12]
    • DD – The day of the month [01-31]
    • hh – The hour of the day [00-23]
    • mm – The minute of the hour [00-59]
    • SS – The second of the minute [00-61]

    Another way to change date and time

    If you feel that the [[CC]YY]MMDDhhmm [.SS] format is not comfortable for you, we can use -d option. Here’s an example how to use -d option.

    Change the date to specific date

    For example we have file named file_3.txt with attributes as shown in the picture below.

    File_3.txt detail timestamp

    Now we want to change the date from 14 January 2014 to 10 December 2013. We can use with this command :

    $ touch -d ‘10-December-2013’ file_3.txt

    Change date using -d option

    We see now that the date for Access and Modify entries is changed into 10 December 2013.

    Change the timezone

    If we want to change it into time in specific GMT, we can also use with -d option. Let’s return the file_3.txt into the current time.

    $ touch file_3.txt

    Reset file_3.txt timestamp

    We can see that file_3.txt has GMT +0700 timezone. To change it into GMT3 timezone, we can use this command.

    $ touch -d GMT3 file_3.txt

    Change into GMT3 timezone

    Now the time is change into 10:00:00 AM

    Combining values using -d option

    There is something cool using -d option. Please take a look at the picture below.

    Change date using keyword

    We can use the word ‘next Sunday’ and combine it with GMT 3 values, and touch command can still recognize it. The date is changed into 21 January 2014, where the current date is 14 January 2014.

    Here’s another example of -d option.
    First, we reset file_3.txt into current date and time.

    $ touch file_3.txt

    Reset file_3.txt timestamp

    Then we do this command :

    $ touch -d ‘1 year ago 13:43:07’ file_3.txt

    Change date using keyword

    Touch even recognize a word ‘1 year ago’. The date and time is now changed into 14 January 2013 and 13:43:07 time.

    Create an empty file

    When you run touch command and the destination file is not exist, then touch will create an empty file with the same name.

    $ touch file_10.txt

    Create an empty file

    Create multiple files at the same time

    To create multiple files, you can put the file names separated by space.

    $ touch doc_10.txt doc_20.txt doc_30.txt

    Create multiple files

    Conclusion

    Touch will useful for you if you are dealing with a timestamp of files and directories. As usual you can always type man touch or touch –help to display its manual page to explore more detail.

  • Linux rm Command Examples – Should be Aware and Cautious

    When a file no longer needed, we may delete it to save storage space. On Linux system, we can use rmcommand to do it.

    What is rm

    rm is a command to delete a file / directory without confirmation by default. Because of this behavior,users should really sure before deleting files.

    Run rm command

    To run rm command, type rm followed by filename. Please remember, that by default rm will not ask any confirmation. Here’s an example of rm in action.

    Remove a file

    $ rm computer.log

    rm command

    To remove a file named computer.log, we can do it with the command above.

    Remove multiple file with specific extension

    If you have multiple file with the same extension and you want to delete them, you can use this syntax :

    $ rm *.log

    rm same extension

    From the above screenshot, all files with .log extension are deleted at the same time.

    Remove a directory

    Removing directory is a little bit tricky. If you are sure that the directory is empty, then we can use -dparameter to remove it.

    $ rm -d documents/

    Remove empty directory

    But when the directory is not empty, you have to empty the directory first, or you can remove them recursively. To remove recursively, use -r or -R parameter.

    $ rm -r movie/

    Remove directory

    Add interactive confirmation before deleting

    If you feel more comfortable to have interactive confirmation, you can use -i parameter with rm command. Here’s a sample of deleting directory recursively with interactive confirmation.

    $ rm -ri movie/

    Interactive remove

    Using force deletion

    Using force deletion mean that rm will remove all files without any confirmation, even the file is write-protected or not. Here’s some samples.

    Remove file with write-protected access

    Force remove

    We see that movie.list has acces read-only for owner, group owner and everyone. When we tried to remove it, rm will ask a confirmation about it, but the file is successfully deleted. Using -f parameter, rm will not ask any confirmation. Take a look at screenshot below.

    Force remove

    But if the directory where the files is located is write-protected, then the file cannot be removed, even the file itself is not write-protected.

    Force remove

    Conclusion

    We always should be careful when we want to delete something. Once again, by default rm command will not ask any confirmation when it delete something. As usual, you can always type man rm or rm –help to display rm manual page and explore it more detail.

  • 15 Linux cp Command Examples – Create a Copy of Files and Directories

    Copying files or directories is one of basic activity in every operating system. Backup activity is basically is creating a copy of files and directories. On Linux system, we can use cp command to do it.

    What is copy command

    As we mentioned above, cp command is a command to create copy of files and directories. Here’s some samples of cp command that might useful in day-to-day operation

    1. Run cp without any options

    This is a very basic cp usage. To copy a file name myfile.txt from one location to another location, we can type like this :

    $ cp myfile.txt /home/pungki/office

    Copy without options

    If we don’t type absolute path, it mean that we are copying a file on current directory. From example above,myfile.txt is located in /home/pungki/Documents. We don’t have to type/home/pungki/Documents/myfile.txt to copy myfile.txt if we are in that /home/pungki/Documentsdirectory. While /home/pungki/office is a folder where the file will be copied.

    2. Copy multiple files at the same time

    To copy multiple file at the same time, we can just put the files behind the copy command which separated by space. Here’s an example :

    $ cp file_1.txt file_2.txt file_3.txt /home/pungki/office

    Copying multiple files

    3. Copy a directory

    Copying a directory is a little bit tricky. You need to add -r or -R option to do it. -r or -R option means recursive. This option is a must whether the directory is empty or not. Here’s an example :

    $ cp -r directory_1 /home/pungki/office

    Copy directory

    One more thing to note is that you need to remove the trailing slash behind the directory name. Otherwise you will have an error message like cp : omitting directory ‘directory_1/’

    Copy directory error

    If you got that error, the directory will not copied to the destination folder.

    4. Create hard links to files instead of copying them

    Copying file means you must have some space on the storage to store the copied files. Sometimes for any reasons, you may want to create “shortcut” or links to the files instead of copying them. To do this, we can use -l option.

    $ cp -l file_4.txt /home/pungki/office

    Copy hardlinks

    From screenshot above, we see that a hardlink of file_4.txt was copied into /home/pungki/office/file_4.txt. It marked by the same inode, 835386. But please note, hardlinks cannot be created into directories. Let’s take a look an example below.

    The original directory_1 has inode number 278230
    Inode number of original directory

    The original file_5.txt has inode number 279231
    Original inode number of file

    Do cp command on directory_1
    Copy using -rl options

    The copied directory_1 has inode number 274800
    Inode number of copied directory

    The copied file_5.txt had inode number 279231. Same with its original file
    Inode number of copied file

    5. Create symbolic links to files

    There is another type of links called softlinks or symbolic links. We use -s option to do this. Here’s a sample command.

    $ cp -s /home/pungki/Documents/file_6.txt file_6.txt

    Creating symlinks only can be done in current directory. On screenshot above, we want to create symbolic links from source directory – /home/pungki/Documents/file_6.txt to /home/pungki/office. But to create symbolic links, I must inside /home/pungki/office as a destination folder. Once I manage to be there, I can run cp -s command above.

    Then when you list the file with detail, you will see that /home/pungki/office/file_6.txt is pointing to the original file. Its marked with arrow sign after the file name.

    Symbolic links

    6. Copy without following symbolic links in Source

    To do this, we can use -P option. When cp command found a file with symbolic links, it will copy the as is. Take a look at the sample below.

    $ cp -P file_6.txt ./movie

    Copy using -P option

    As you can see, the cp command will copy file_6.txt as is. The file type still a symbolic link.

    7. Copy with following symbolic links in Source

    Now we can do this with -L option. Basically, this is an opposite of -P option above. Here’s the sample.

    $ cp -L file_6.txt ./movie

    Copy using -L option

    With this option, the copied file is the same file with the source file of file_6.txt. This is known from the file size. The copied file has 50 bytes file size while the file_6.txt as symbolic link has 33 bytes file size.

    8. Archive the files

    When we are going to copy a directory, we will use -r or -R option. But we can also use -a option to archive file. This will create an exact copy of files and directories including symbolic links if any. Here’s a sample :

    $ cp -a directory_1/ /home/pungki/office

    Copy using -a option

    The above command will copy a directory named directory_1 into folder /home/pungki/office. As you can see, the file_6.txt still copied as symbolic links.

    9. Explain what is being done

    By default, when copying activity is success, we will see a command prompt again. If you want to know what happen during the copying file, we can use -v option.

    $ cp -v *.txt /home/pungki/office

    Verbose option

    When we copying all txt files in current directory to /home/pungki/office/ directory, -v option will show what is being done. This additional information will make us more sure about the copying activity.

    10. Copy only when the source file is newer

    To do this, we can use -u option. Take a look this example below.

    $ cp -vu *.txt /home/pungki/office

    Copy only if newer

    In the beginning, we see file_1.txt has 0 bytes file size. Then we edit it using vi, add some content and save it. Next, we see the file size has changed into 36 bytes.
    Meanwhile in /home/pungki/office directory, we already have all *.txt files. When we use -u option, combine with -v option to see what is being done, cp command will only copy a file(s) which is newer from destination directory. As the result, we see that only file_1.txt is copied into /home/pungki/office directory.

    11. Use interactive mode

    Interactive mode will ask if the destination folder have already the file. To activate interactive mode, use -ioption.

    $ cp -ir directory_1/ /home/pungki/office/

    Interactive mode

    12. Create backup date of each copied file

    When the destination folder already have the file, by default cp command will overwrite the same file in the destination directory. Using –backup option, cp command will make a backup of each existing destination file. ../office will refer to /home/pungki/office. Here’s a sample :

    $ cp –backup=simple -v *.txt ../office

    Backup option

    As we can see, –backup=simple option will create a backup file which marked by a tilde sign (~) at the end of the file. –backup option has some Control, which are :

    • none, off : never backups (even if –backup is given)
    • numbered, t : make numbered backups
    • existing, nil : numbered if numbered backup exist, simple otherwise
    • simple, never : always make simple backups

    13. Copy only file attributes

    Cp command also provide us with –attributes-only option. As we can guess from its name, this option will only copy a file name and its attributes without copying any data. Here’s a sample.

    $ cp –attributes-only file_6.txt -v ../office

    Copy attributes only

    From screenshot above, the original file_6.txt file has 50 bytes file size. Using –attributes-only option,the copied file will have 0 bytes file size. This is because the content of file is not being copied.

    14. Force copying

    Using -f option will force the copying activity. If the destination files cannot be opened, then -f will try again.

    $ cp -f *.txt -v ../office

    Copy with force

    15. Remove destination before copy

    To do this, we can use –remove-destination option. This option is contrast with -f option above. If the cp command find the same file name on the destination folder, cp command will remove destination file first, the copy the new one. Here’s an example.

    $ cp –remove-destination *.txt -v ../office

    Remove destination option

    Conclusion

    Cp command is one of basic Linux commands. For those who want to learn Linux, must know this command. Of course you can type man cp or cp –help from your console to display its manual page to explore more detail.

  • Tee Command Usage Examples

    Tee command is used to store and view (both at the same time) the output of any other command.

    Tee command writes to the STDOUT, and to a file at a time as shown in the examples below.

    Example 1: Write output to stdout, and also to a file

    The following command displays output only on the screen (stdout).

    $ ls 
    
    

    The following command writes the output only to the file and not to the screen.

    $ ls > file
    

    The following command (with the help of tee command) writes the output both to the screen (stdout) and to the file.

    $ ls | tee file
    

    Example 2: Write the output to two commands

    You can also use tee command to store the output of a command to a file and redirect the same output as an input to another command.

    The following command will take a backup of the crontab entries, and pass the crontab entries as an input to sed command which will do the substituion. After the substitution, it will be added as a new cron job.

    $ crontab -l | tee crontab-backup.txt | sed 's/old/new/' | crontab –
    

    Misc Tee Command Operations

    By default tee command overwrites the file. You can instruct tee command to append to the file using the option –a as shown below.

    $ ls | tee –a file
    

    You can also write the output to multiple files as shown below.

    $ ls | tee file1 file2 file3
    
    

    Example : How To Use Tee Command In Linux

    In Unix and Linux world, a large number of small, single purpose programs are available. These programs can be chained together to perform complex tasks. Command chaining and redirection are the features that are used for these complex tasks. You can redirect the output and/or errors to a file and it will not be shown on the terminal. Similarly, using chaining, output of one command can be given as input to second command and further to third command and so on. But once you redirect an output to a file, you cannot chain it with other command. Tee command can be used to achieve both of these results together, i.e. store the result to a file while chaining the same output to another command.

    Tee command

    By default tee command reads from standard input, and writes to standard output and files. Let us see an example of tee command:

    $ ls / | tee rootlisting.txt
    bin
    boot
    cdrom
    dev
    etc
    home
    initrd.img
    initrd.img.old
    lib
    lost+found
    media
    mnt
    opt
    proc
    root
    sbin
    selinux
    srv
    sys
    tmp
    usr
    var
    vmlinuz
    vmlinuz.old

    In this example, the tee command stores the output of “ls /” command in a file named rootlisting.txt and to standard output as well. With tee command, you can store intermediate results of the commands in different stages of chaining as:

    $ ls /etc | tee stage1.txt | grep ^s | tee stage2.txt | sort -r
    sysctl.d
    sysctl.conf
    sudoers.d
    sudoers
    ssl
    ssh
    speech-dispatcher
    sound
    snmp
    smi.conf
    skel
    shells
    shadow-
    shadow
    sgml
    services
    sensors.d
    sensors3.conf
    security
    securetty
    sane.d
    samba

    Here, first /etc directory is listed, and then output is stored in the file named stage1.txt. This output is filtered through grep for the lines starting with letter s. This filtered output is stored in the file stage2.txt. Finally, the filtered output is reverse sorted using sort -r command. This final output is displayed on the terminal. Thus tee command is used to store intermediate results to files.
    The tee command can store the output to more than one file:

    $ ls /etc | grep ^s | tee file1.txt file2.txt | sort -r
    sysctl.d
    sysctl.conf
    sudoers.d
    sudoers
    ssl
    ssh
    speech-dispatcher
    sound
    snmp
    smi.conf
    skel
    shells
    shadow-
    shadow
    sgml
    services
    sensors.d
    sensors3.conf
    security
    securetty
    sane.d
    samba

    $ ls -l file*
    -rw-r–r– 1 raghu raghu 182 2012-08-19 13:07 file1.txt
    -rw-r–r– 1 raghu raghu 182 2012-08-19 13:07 file2.txt

    In this example, the output if grep filter is stored in two files: file1.txt and file2.txt.
    Tee command by default overwrites any content in the file. The output can be appended to the file with -a option.

    $ ls /boot/ | tee -a file1.txt
    abi-2.6.38-12-generic
    abi-2.6.38-13-generic
    abi-2.6.38-8-generic
    config-2.6.38-12-generic
    config-2.6.38-13-generic
    config-2.6.38-8-generic
    grub
    initrd.img-2.6.38-12-generic
    initrd.img-2.6.38-13-generic
    initrd.img-2.6.38-8-generic
    memtest86+.bin
    memtest86+_multiboot.bin
    System.map-2.6.38-12-generic
    System.map-2.6.38-13-generic
    System.map-2.6.38-8-generic
    vmcoreinfo-2.6.38-12-generic
    vmcoreinfo-2.6.38-13-generic
    vmcoreinfo-2.6.38-8-generic
    vmlinuz-2.6.38-12-generic
    vmlinuz-2.6.38-13-generic
    vmlinuz-2.6.38-8-generic

    You can check the contents of the file named file1.txt to confirm your result.

    $ cat file1.txt
    samba
    sane.d
    securetty
    security
    sensors3.conf
    sensors.d
    services
    sgml
    shadow
    shadow-
    shells
    skel
    smi.conf
    snmp
    sound
    speech-dispatcher
    ssh
    ssl
    sudoers
    sudoers.d
    sysctl.conf
    sysctl.d
    abi-2.6.38-12-generic
    abi-2.6.38-13-generic
    abi-2.6.38-8-generic
    config-2.6.38-12-generic
    config-2.6.38-13-generic
    config-2.6.38-8-generic
    grub
    initrd.img-2.6.38-12-generic
    initrd.img-2.6.38-13-generic
    initrd.img-2.6.38-8-generic
    memtest86+.bin
    memtest86+_multiboot.bin
    System.map-2.6.38-12-generic
    System.map-2.6.38-13-generic
    System.map-2.6.38-8-generic
    vmcoreinfo-2.6.38-12-generic
    vmcoreinfo-2.6.38-13-generic
    vmcoreinfo-2.6.38-8-generic
    vmlinuz-2.6.38-12-generic
    vmlinuz-2.6.38-13-generic
    vmlinuz-2.6.38-8-generic

    EXAMPLES

    1. Write output to stdout, and also to a file

    The following command displays output only on the screen (stdout).

    $ ls

    The following command writes the output only to the file and not to the screen.

    $ ls > file

    The following command (with the help of tee command) writes the output both to the screen (stdout) and to the file.

    $ ls | tee file1.txt

    2. You can instruct tee command to append to the file using the option –a as shown below

    $ ls | tee –a fileq.txt

    3. You can also write the output to multiple files as shown below.

    $ ls | tee file1 file2 file3

    4. Write the output to two commands

    You can also use tee command to store the output of a command to a file and redirect the same output as an input to another command.

    The following command will long list directory contents, store it in abc.txt and then count the no. of lines and echo it

    $ ls -l | tee abc.txt | wc -l
    
    

    Linux Redirect Error Output To File

    Iam a new Ubuntu Linux and bash shell user. I also know how to redirect output from display/screen to a file using the following syntax:

    cmd > file
    ls > file

    However, some time errors are displayed on screen. How do I store and redirect output from the computer screen to a file on a Linux or Unix-like systems?

    Bash / ksh and other modern shell on Linux has three file descriptors:

    1. stdin (0)
    2. stdout (1)
    3. stderr (2)

    Syntax To redirect all output to file

    The syntax is as follows to redirect output (stdout) as follows:

     
    command-name >  output.txt
    command-name >  stdout.txt
    

    Syntax To redirect all error to file

    The syntax is as follows to redirect errors (stderr) as follows:

     
    command-name 2> errors.txt
    command-name 2> stderr.txt
    

    Syntax to redirect both output (stdout) and errors (stderr) to different files

    The syntax:

     
    command1 > out.txt 2> err.txt
    command2 -f -z -y > out.txt 2> err.txt
    

    Syntax to redirect both output (stdout) and errors (stderr) to same file

    The syntax is:

     
    command1 > everything.txt 2>&1
    command1 -arg > everything.txt 2>&1
    

    Syntax to redirect errors (stderr) to null or zero devices

    Data written to a null or zero special file is discarded by your system. This is useful to silence out errors (also know as ‘error spam’):

     
    command1 2> /dev/null
    command1 2> /dev/zero
    command2 -arg 2> /dev/null
    command2 -arg 2> /dev/zero
    

    Tip: Use tee command to redirect to both a file and the screen same time

    The syntax is:

     
    command1 |& tee log.txt
    ## or ##
    command1 -arg |& tee log.txt
    ## or ##
    command1 2>&1 | tee log.txt
    

    Another usage:

    #!/bin/bash
    # My script to do blah ...
    foo(){
     :
    } 2>&1 | tee foo.log
    

    OR

    #!/bin/bash
    # My script to do blah ...
    {
       command1
       command2
    } 2>&1 | tee script.log
    
    
    
  • “unexpand” Command Usage Example in Linux

    Examples :

    1. Basic Example

    $ cat -vet file2
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$
    One     Two     Three   Four    Five    six     seven$

    By using the “cat -vet” option against file1, we can see that the tabs are represented by the “I^” character.The “$” denotes a line feed.

    $ unexpand -a file2 > file3
    $ cat -vet file3
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$
    One^ITwo^IThree^IFour^IFive^Isix^Iseven$

    Hece the spaces are converted into tabs.

  • Sed Command in Unix and Linux Examples

    Sed is a Stream Editor used for modifying the files in unix (or linux). Whenever you want to make changes to the file automatically, sed comes in handy to do this. Most people never learn its power; they just simply use sed to replace text. You can do many things apart from replacing text with sed. Here I will describe the features of sed with examples.

    Consider the below text file as an input.

    >cat file.txt
    unix is great os. unix is opensource. unix is free os.
    learn operating system.
    unixlinux which one you choose.
    

    Sed Command Examples

    1. Replacing or substituting string

    Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.

    >sed 's/unix/linux/' file.txt
    linux is great os. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you choose.
    

    Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string.

    By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third…occurrence in the line.

    2. Replacing the nth occurrence of a pattern in a line.

    Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.

    >sed 's/unix/linux/2' file.txt
    unix is great os. linux is opensource. unix is free os.
    learn operating system.
    unixlinux which one you choose.
    

    3. Replacing all the occurrence of the pattern in a line.

    The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.

    >sed 's/unix/linux/g' file.txt
    linux is great os. linux is opensource. linux is free os.
    learn operating system.
    linuxlinux which one you choose.
    

    4. Replacing from nth occurrence to all occurrences in a line.

    Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth… “unix” word with “linux” word in a line.

    >sed 's/unix/linux/3g' file.txt
    unix is great os. unix is opensource. linux is free os.
    learn operating system.
    unixlinux which one you choose.
    

    5. Changing the slash (/) delimiter

    You can use any delimiter other than the slash. As an example if you want to change the web url to another url as

    >sed 's/http:\/\//www/' file.txt
    

    In this case the url consists the delimiter character which we used. In that case you have to escape the slash with backslash character, otherwise the substitution won’t work.

    Using too many backslashes makes the sed command look awkward. In this case we can change the delimiter to another character as shown in the below example.

    >sed 's_http://_www_' file.txt
    >sed 's|http://|www|' file.txt
    

    6. Using & as the matched string

    There might be cases where you want to search for the pattern and replace that pattern by adding some extra characters to it. In such cases & comes in handy. The & represents the matched string.

    >sed 's/unix/{&}/' file.txt
    {unix} is great os. unix is opensource. unix is free os.
    learn operating system.
    {unix}linux which one you choose.
    
    >sed 's/unix/{&&}/' file.txt
    {unixunix} is great os. unix is opensource. unix is free os.
    learn operating system.
    {unixunix}linux which one you choose.
    

    7. Using \1,\2 and so on to \9

    The first pair of parenthesis specified in the pattern represents the \1, the second represents the \2 and so on. The \1,\2 can be used in the replacement string to make changes to the source string. As an example, if you want to replace the word “unix” in a line with twice as the word like “unixunix” use the sed command as below.

    >sed 's/\(unix\)/\1\1/' file.txt
    unixunix is great os. unix is opensource. unix is free os.
    learn operating system.
    unixunixlinux which one you choose.
    

    The parenthesis needs to be escaped with the backslash character. Another example is if you want to switch the words “unixlinux” as “linuxunix”, the sed command is

    >sed 's/\(unix\)\(linux\)/\2\1/' file.txt
    unix is great os. unix is opensource. unix is free os.
    learn operating system.
    linuxunix which one you choose.
    

    Another example is switching the first three characters in a line

    >sed 's/^\(.\)\(.\)\(.\)/\3\2\1/' file.txt
    inux is great os. unix is opensource. unix is free os.
    aelrn operating system.
    inuxlinux which one you choose.
    

    8. Duplicating the replaced line with /p flag

    The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.

    >sed 's/unix/linux/p' file.txt
    linux is great os. unix is opensource. unix is free os.
    linux is great os. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you choose.
    linuxlinux which one you choose.
    

    9. Printing only the replaced lines

    Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.

    >sed -n 's/unix/linux/p' file.txt
    linux is great os. unix is opensource. unix is free os.
    linuxlinux which one you choose.
    

    If you use -n alone without /p, then the sed does not print anything.

    10. Running multiple sed commands.

    You can run multiple sed commands by piping the output of one sed command as input to another sed command.

    >sed 's/unix/linux/' file.txt| sed 's/os/system/'
    linux is great system. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you chosysteme.
    

    Sed provides -e option to run multiple sed commands in a single sed command. The above output can be achieved in a single sed command as shown below.

    >sed -e 's/unix/linux/' -e 's/os/system/' file.txt
    linux is great system. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you chosysteme.
    

    11. Replacing string on a specific line number.

    You can restrict the sed command to replace the string on a specific line number. An example is

    >sed '3 s/unix/linux/' file.txt
    unix is great os. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you choose.
    

    The above sed command replaces the string only on the third line.

    12. Replacing string on a range of lines.

    You can specify a range of line numbers to the sed command for replacing a string.

    >sed '1,3 s/unix/linux/' file.txt
    linux is great os. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you choose.
    

    Here the sed command replaces the lines with range from 1 to 3. Another example is

    >sed '2,$ s/unix/linux/' file.txt
    linux is great os. unix is opensource. unix is free os.
    learn operating system.
    linuxlinux which one you choose.
    

    Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.

    13. Replace on a lines which matches a pattern.

    You can specify a pattern to the sed command to match in a line. If the pattern match occurs, then only the sed command looks for the string to be replaced and if it finds, then the sed command replaces the string.

    >sed '/linux/ s/unix/centos/' file.txt
    unix is great os. unix is opensource. unix is free os.
    learn operating system.
    centoslinux which one you choose.
    

    Here the sed command first looks for the lines which has the pattern “linux” and then replaces the word “unix” with “centos”.

    14. Deleting lines.

    You can delete the lines a file by specifying the line number or a range or numbers.

    >sed '2 d' file.txt
    >sed '5,$ d' file.txt
    

    15. Duplicating lines

    You can make the sed command to print each line of a file two times.

    >sed 'p' file.txt
    

    16. Sed as grep command

    You can make sed command to work as similar to grep command.

    >grep 'unix' file.txt
    >sed -n '/unix/ p' file.txt
    

    Here the sed command looks for the pattern “unix” in each line of a file and prints those lines that has the pattern.

    You can also make the sed command to work as grep -v, just by using the reversing the sed with NOT (!).

    >grep -v 'unix' file.txt
    >sed -n '/unix/ !p' file.txt
    

    The ! here inverts the pattern match.

    17. Add a line after a match.

    The sed command can add a new line after a pattern match is found. The “a” command to sed tells it to add a new line after a match is found.

    >sed '/unix/ a "Add a new line"' file.txt
    unix is great os. unix is opensource. unix is free os.
    "Add a new line"
    learn operating system.
    unixlinux which one you choose.
    "Add a new line"
    

    18. Add a line before a match

    The sed command can add a new line before a pattern match is found. The “i” command to sed tells it to add a new line before a match is found.

    >sed '/unix/ i "Add a new line"' file.txt
    "Add a new line"
    unix is great os. unix is opensource. unix is free os.
    learn operating system.
    "Add a new line"
    unixlinux which one you choose.
    

    19. Change a line

    The sed command can be used to replace an entire line with a new line. The “c” command to sed tells it to change the line.

    >sed '/unix/ c "Change line"' file.txt
    "Change line"
    learn operating system.
    "Change line"
    

    20. Transform like tr command

    The sed command can be used to convert the lower case letters to upper case letters by using the transform “y” option.

    >sed 'y/ul/UL/' file.txt
    Unix is great os. Unix is opensoUrce. Unix is free os.
    Learn operating system.
    UnixLinUx which one yoU choose.
    

    Here the sed command transforms the alphabets “ul” into their uppercase format “UL”

  • “fmt” Command Usage Examples in Linux

    EXAMPLES

    1. Given the contents of file file1.txt, fmt works as follows

    $ cat file1.txt
    abc
    def
    ghi
    $ fmt file1.txt
    abc def ghi

    Simply using fmt formats text in a single line.

    2. Let abc file contains some text, then giving a width of 1 produces output

    $ cat abc
      This is a brief message to the Control Unit group.
         The new hp is now on-line. To send prints to it, type lj filename.
         If you have questions contact Sys. Adm. (x480).  The printer is
         located in the stock room.
    $ fmt -w 1  abc
      This
      is
      a
      brief
      message
      to
      the
      Control
      Unit
      group.
         The
         new
         hp
         is
         now
         on-line.
         To
         send
         prints
         to
         it,
         type
         lj
         filename.
         If
         you
         have
         questions
         contact
         Sys.
         Adm.
         (x480).
         The
         printer
         is
         located
         in
         the
         stock
         room.

    3. Crown Margin Mode

    This example shows the crown margin usage.

    $ cat abc
      This is a brief message to the Control Unit group.
         The new hp is now on-line. To send prints to it, type lj filename.
         If you have questions contact Sys. Adm. (x480).
         The printer is located in the stock room.
    $ fmt -c abc
      This is a brief message to the Control Unit group.  The new hp is
         now on-line. To send prints to it, type lj filename.  If you have
         questions contact Sys. Adm. (x480).  The printer is located in the
         stock room.
  • 9 Linux Uname Command Examples To Get Operating System Details

    When you are in console mode, there is no ‘Right click > About’ to give you information about your operating system. In Linux, you can use command uname to help you about that. Uname is the short name for unixname. Just type uname in console.

    When you type uname without parameter, it will only show the name of your operating system.

    # uname
    Linux

    It may not satisfy what you need. So you may need to use some parameters to make uname show the information you need.

    Here’s the list of uname parameters :

    1. Kernel name

    To reveal the kernel name, you can use -s parameter.

    # uname -s
    Linux

    The output will be same with uname without parameter.

    2. Kernel release

    If you need to know what kernel release you’re using, just use -r parameter

    # uname -r
    2.6.18-371.1.2.el5

    3. Kernel version

    Beside kernel information, uname can also fetch the kernel version. Use -v parameter for this purpose

    # uname -v
    #1 SMP Tue Oct 22 12:57:43 EDT 2013

    4. Nodename

    Parameter -n will give you the node hostname. For example, if your hostname is “dev-machine”, -nparameter will print dev-machine as the output of -n parameter

    # uname -n
    dev-machine

    For RedHat and CentOS, you can also use /etc/redhat_release file :

    # cat /etc/redhat_release
    CentOS release 5.10 (Final)

    For non-RedHat based distro, you may use /etc/issue. Here’s the example :

    # cat /etc/issue
    Linux Mint Olivia \n \l

    5. Hardware name

    If you are wondering what kind of machine you’re using, you can try -m parameter. It will show you information about it.

    # uname -m
    i686

    i686 is indicates that your system is 32 bit operating system. While x86_64 means your system is a 64 bit system.

    6. Hardware platform

    Similar with hardware name, -i parameter will show you hardware platfrom.

    # uname -i
    i386

    i386 mean you are running a 32 bit system. If the output is x86_64 it’s mean that you are running 64 bis system.

    7. Processor type

    To see processor type, you can use -p parameter. If uname is not able to show you that information, it will show you ‘unknown’ in the output.

    # uname -p
    i686

    8. Operating system

    Uname can also used to reveal what operating system you are running. Use -o parameter to fulfill this purpose.

    # uname -o
    GNU/Linux

    9. All information

    There is one parameter that can reveal all information. It’s -a parameter. It will show you all informationexcept omit -i and -p if they are unknown.

    # uname -a
    Linux dev-machine 2.6.18-371.1.2.el5 #1 SMP Tue Oct 22 12:57:43 EDT 2013 i686 i686 i386 GNU/Linux

    That’s the uname command in use.