DEV Community

shun
shun

Posted on

File and Directory Operations in Linux Commands

Creating and Removing

  • touch: Create an empty file.
  $ touch newfile.txt
Enter fullscreen mode Exit fullscreen mode
  • mkdir: Create a new directory.
  $ mkdir new_directory
Enter fullscreen mode Exit fullscreen mode
  • rm: Remove files.

    • -r (or --recursive): Remove directories and their contents.
    • -f: Force removal without confirmation.
    $ rm file_to_remove.txt
    $ rm -rf directory_to_remove/
    
  • rmdir: Remove an empty directory.

  $ rmdir empty_directory
Enter fullscreen mode Exit fullscreen mode

Copying, Moving, and Renaming

  • cp: Copy files or directories.

    • -r: Recursively copy directories.
    • -i: Prompt before overwriting files.
    $ cp source.txt destination.txt
    $ cp -ri source_directory/ destination_directory/
    
  • mv: Move or rename files or directories.

    • -i: Prompt before overwriting files.
    $ mv -i oldname.txt newname.txt
    

Listing and Navigating

  • ls: List directory contents.

    • -l: Display in long format.
    • -a: Show hidden files.
    • -h: Display sizes in human-readable format.
    $ ls -lah
    
  • pwd: Print the current working directory.

  $ pwd
Enter fullscreen mode Exit fullscreen mode
  • cd: Change the current directory.
  $ cd /path/to/directory/
Enter fullscreen mode Exit fullscreen mode

File Content Viewing

  • cat: Display the entire content of a file.
  $ cat file.txt
  This is the content of file.txt.
Enter fullscreen mode Exit fullscreen mode
  • less: View file content with pagination. No direct output, but provides an interactive view.
  $ less file.txt
Enter fullscreen mode Exit fullscreen mode
  • head: Display the beginning of a file.
  $ head file.txt
  First line of the file.
Enter fullscreen mode Exit fullscreen mode
  • tail: Display the end of a file.

    • -f: Follow the content of a file in real-time.
    $ tail -f /var/log/syslog
    Aug 11 12:34:56 hostname program[1234]: Log message here.
    

File and Directory Information

  • stat: Display detailed information about a file or directory.
  $ stat file.txt
  File: file.txt
  Size: 1234       Blocks: 8          IO Block: 4096   regular file
  Device: 801h/2049d      Inode: 123456      Links: 1
  Access: (0644/-rw-r--r--)  Uid: ( 1000/    user)   Gid: ( 1000/    user)
Enter fullscreen mode Exit fullscreen mode
  • file: Determine the type of a file.
  $ file image.jpg
  image.jpg: JPEG image data, JFIF standard 1.01
Enter fullscreen mode Exit fullscreen mode

Searching for Files

  • find: Search for files in a directory hierarchy.
  $ find /path/to/search/ -name "pattern*"
  /path/to/search/pattern1.txt
  /path/to/search/subdir/pattern2.txt
Enter fullscreen mode Exit fullscreen mode

Top comments (0)