{"id":15410761,"url":"https://github.com/rehansaeed/bash-cheat-sheet","last_synced_at":"2026-02-02T12:09:50.650Z","repository":{"id":37314236,"uuid":"199469192","full_name":"RehanSaeed/Bash-Cheat-Sheet","owner":"RehanSaeed","description":" A cheat sheet for bash commands.","archived":false,"fork":false,"pushed_at":"2023-12-12T05:38:32.000Z","size":39,"stargazers_count":1001,"open_issues_count":4,"forks_count":338,"subscribers_count":17,"default_branch":"main","last_synced_at":"2025-01-11T14:23:41.032Z","etag":null,"topics":["bash","cheat-sheet","linux","sh","shell","tar","unix"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RehanSaeed.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2019-07-29T14:30:12.000Z","updated_at":"2025-01-10T10:21:19.000Z","dependencies_parsed_at":"2024-02-12T04:45:15.339Z","dependency_job_id":null,"html_url":"https://github.com/RehanSaeed/Bash-Cheat-Sheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RehanSaeed%2FBash-Cheat-Sheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RehanSaeed%2FBash-Cheat-Sheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RehanSaeed%2FBash-Cheat-Sheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RehanSaeed%2FBash-Cheat-Sheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RehanSaeed","download_url":"https://codeload.github.com/RehanSaeed/Bash-Cheat-Sheet/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241255117,"owners_count":19934815,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bash","cheat-sheet","linux","sh","shell","tar","unix"],"created_at":"2024-10-01T16:46:14.848Z","updated_at":"2026-02-02T12:09:50.579Z","avatar_url":"https://github.com/RehanSaeed.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Bash Cheat Sheet\r\n\r\n A cheat sheet for bash commands.\r\n\r\n## Command History\r\n\r\n```bash\r\n!!            # Run the last command\r\n\r\ntouch foo.sh\r\nchmod +x !$   # !$ is the last argument of the last command i.e. foo.sh\r\n```\r\n\r\n## Navigating Directories\r\n\r\n```bash\r\npwd                       # Print current directory path\r\nls                        # List directories\r\nls -a|--all               # List directories including hidden\r\nls -l                     # List directories in long form\r\nls -l -h|--human-readable # List directories in long form with human readable sizes\r\nls -t                     # List directories by modification time, newest first\r\nstat foo.txt              # List size, created and modified timestamps for a file\r\nstat foo                  # List size, created and modified timestamps for a directory\r\ntree                      # List directory and file tree\r\ntree -a                   # List directory and file tree including hidden\r\ntree -d                   # List directory tree\r\ncd foo                    # Go to foo sub-directory\r\ncd                        # Go to home directory\r\ncd ~                      # Go to home directory\r\ncd -                      # Go to last directory\r\npushd foo                 # Go to foo sub-directory and add previous directory to stack\r\npopd                      # Go back to directory in stack saved by `pushd`\r\n```\r\n\r\n## Creating Directories\r\n\r\n```bash\r\nmkdir foo                        # Create a directory\r\nmkdir foo bar                    # Create multiple directories\r\nmkdir -p|--parents foo/bar       # Create nested directory\r\nmkdir -p|--parents {foo,bar}/baz # Create multiple nested directories\r\n\r\nmktemp -d|--directory            # Create a temporary directory\r\n```\r\n\r\n## Moving Directories\r\n\r\n```bash\r\ncp -R|--recursive foo bar                               # Copy directory\r\nmv foo bar                                              # Move directory\r\n\r\nrsync -z|--compress -v|--verbose /foo /bar              # Copy directory, overwrites destination\r\nrsync -a|--archive -z|--compress -v|--verbose /foo /bar # Copy directory, without overwriting destination\r\nrsync -avz /foo username@hostname:/bar                  # Copy local directory to remote directory\r\nrsync -avz username@hostname:/foo /bar                  # Copy remote directory to local directory\r\n```\r\n\r\n## Deleting Directories\r\n\r\n```bash\r\nrmdir foo                        # Delete empty directory\r\nrm -r|--recursive foo            # Delete directory including contents\r\nrm -r|--recursive -f|--force foo # Delete directory including contents, ignore nonexistent files and never prompt\r\n```\r\n\r\n## Creating Files\r\n\r\n```bash\r\ntouch foo.txt          # Create file or update existing files modified timestamp\r\ntouch foo.txt bar.txt  # Create multiple files\r\ntouch {foo,bar}.txt    # Create multiple files\r\ntouch test{1..3}       # Create test1, test2 and test3 files\r\ntouch test{a..c}       # Create testa, testb and testc files\r\n\r\nmktemp                 # Create a temporary file\r\n```\r\n\r\n## Standard Output, Standard Error and Standard Input\r\n\r\n```bash\r\necho \"foo\" \u003e bar.txt       # Overwrite file with content\r\necho \"foo\" \u003e\u003e bar.txt      # Append to file with content\r\n\r\nls exists 1\u003e stdout.txt    # Redirect the standard output to a file\r\nls noexist 2\u003e stderror.txt # Redirect the standard error output to a file\r\nls 2\u003e\u00261 \u003e out.txt          # Redirect standard output and error to a file\r\nls \u003e /dev/null             # Discard standard output and error\r\n\r\nread foo                   # Read from standard input and write to the variable foo\r\n```\r\n\r\n## Moving Files\r\n\r\n```bash\r\ncp foo.txt bar.txt                                # Copy file\r\nmv foo.txt bar.txt                                # Move file\r\n\r\nrsync -z|--compress -v|--verbose /foo.txt /bar    # Copy file quickly if not changed\r\nrsync z|--compress -v|--verbose /foo.txt /bar.txt # Copy and rename file quickly if not changed\r\n```\r\n\r\n## Deleting Files\r\n\r\n```bash\r\nrm foo.txt            # Delete file\r\nrm -f|--force foo.txt # Delete file, ignore nonexistent files and never prompt\r\n```\r\n\r\n## Reading Files\r\n\r\n```bash\r\ncat foo.txt            # Print all contents\r\nless foo.txt           # Print some contents at a time (g - go to top of file, SHIFT+g, go to bottom of file, /foo to search for 'foo')\r\nhead foo.txt           # Print top 10 lines of file\r\ntail foo.txt           # Print bottom 10 lines of file\r\nopen foo.txt           # Open file in the default editor\r\nwc foo.txt             # List number of lines words and characters in the file\r\n```\r\n\r\n## File Permissions\r\n\r\n| # | Permission              | rwx | Binary |\r\n| - | -                       | -   | -      |\r\n| 7 | read, write and execute | rwx | 111    |\r\n| 6 | read and write          | rw- | 110    |\r\n| 5 | read and execute        | r-x | 101    |\r\n| 4 | read only               | r-- | 100    |\r\n| 3 | write and execute       | -wx | 011    |\r\n| 2 | write only              | -w- | 010    |\r\n| 1 | execute only            | --x | 001    |\r\n| 0 | none                    | --- | 000    |\r\n\r\nFor a directory, execute means you can enter a directory.\r\n\r\n| User | Group | Others | Description                                                                                          |\r\n| -    | -     | -      | -                                                                                                    |\r\n| 6    | 4     | 4      | User can read and write, everyone else can read (Default file permissions)                           |\r\n| 7    | 5     | 5      | User can read, write and execute, everyone else can read and execute (Default directory permissions) |\r\n\r\n- u - User\r\n- g - Group\r\n- o - Others\r\n- a - All of the above\r\n\r\n```bash\r\nls -l /foo.sh            # List file permissions\r\nchmod +100 foo.sh        # Add 1 to the user permission\r\nchmod -100 foo.sh        # Subtract 1 from the user permission\r\nchmod u+x foo.sh         # Give the user execute permission\r\nchmod g+x foo.sh         # Give the group execute permission\r\nchmod u-x,g-x foo.sh     # Take away the user and group execute permission\r\nchmod u+x,g+x,o+x foo.sh # Give everybody execute permission\r\nchmod a+x foo.sh         # Give everybody execute permission\r\nchmod +x foo.sh          # Give everybody execute permission\r\n```\r\n\r\n## Finding Files\r\n\r\nFind binary files for a command.\r\n\r\n```bash\r\ntype wget                                  # Find the binary\r\nwhich wget                                 # Find the binary\r\nwhereis wget                               # Find the binary, source, and manual page files\r\n```\r\n\r\n`locate` uses an index and is fast.\r\n\r\n```bash\r\nupdatedb                                   # Update the index\r\n\r\nlocate foo.txt                             # Find a file\r\nlocate --ignore-case                       # Find a file and ignore case\r\nlocate f*.txt                              # Find a text file starting with 'f'\r\n```\r\n\r\n`find` doesn't use an index and is slow.\r\n\r\n```bash\r\nfind /path -name foo.txt                   # Find a file\r\nfind /path -iname foo.txt                  # Find a file with case insensitive search\r\nfind /path -name \"*.txt\"                   # Find all text files\r\nfind /path -name foo.txt -delete           # Find a file and delete it\r\nfind /path -name \"*.png\" -exec pngquant {} # Find all .png files and execute pngquant on it\r\nfind /path -type f -name foo.txt           # Find a file\r\nfind /path -type d -name foo               # Find a directory\r\nfind /path -type l -name foo.txt           # Find a symbolic link\r\nfind /path -type f -mtime +30              # Find files that haven't been modified in 30 days\r\nfind /path -type f -mtime +30 -delete      # Delete files that haven't been modified in 30 days\r\n```\r\n\r\n## Find in Files\r\n\r\n```bash\r\ngrep 'foo' /bar.txt                         # Search for 'foo' in file 'bar.txt'\r\ngrep 'foo' /bar -r|--recursive              # Search for 'foo' in directory 'bar'\r\ngrep 'foo' /bar -R|--dereference-recursive  # Search for 'foo' in directory 'bar' and follow symbolic links\r\ngrep 'foo' /bar -l|--files-with-matches     # Show only files that match\r\ngrep 'foo' /bar -L|--files-without-match    # Show only files that don't match\r\ngrep 'Foo' /bar -i|--ignore-case            # Case insensitive search\r\ngrep 'foo' /bar -x|--line-regexp            # Match the entire line\r\ngrep 'foo' /bar -C|--context 1              # Add N line of context above and below each search result\r\ngrep 'foo' /bar -v|--invert-match           # Show only lines that don't match\r\ngrep 'foo' /bar -c|--count                  # Count the number lines that match\r\ngrep 'foo' /bar -n|--line-number            # Add line numbers\r\ngrep 'foo' /bar --colour                    # Add colour to output\r\ngrep 'foo\\|bar' /baz -R                     # Search for 'foo' or 'bar' in directory 'baz'\r\ngrep --extended-regexp|-E 'foo|bar' /baz -R # Use regular expressions\r\negrep 'foo|bar' /baz -R                     # Use regular expressions\r\n```\r\n\r\n### Replace in Files\r\n\r\n```bash\r\nsed 's/fox/bear/g' foo.txt               # Replace fox with bear in foo.txt and output to console\r\nsed 's/fox/bear/gi' foo.txt              # Replace fox (case insensitive) with bear in foo.txt and output to console\r\nsed 's/red fox/blue bear/g' foo.txt      # Replace red with blue and fox with bear in foo.txt and output to console\r\nsed 's/fox/bear/g' foo.txt \u003e bar.txt     # Replace fox with bear in foo.txt and save in bar.txt\r\nsed 's/fox/bear/g' foo.txt -i|--in-place # Replace fox with bear and overwrite foo.txt\r\n```\r\n\r\n## Symbolic Links\r\n\r\n```bash\r\nln -s|--symbolic foo bar            # Create a link 'bar' to the 'foo' folder\r\nln -s|--symbolic -f|--force foo bar # Overwrite an existing symbolic link 'bar'\r\nls -l                               # Show where symbolic links are pointing\r\n```\r\n\r\n## Compressing Files\r\n\r\n### zip\r\n\r\nCompresses one or more files into *.zip files.\r\n\r\n```bash\r\nzip foo.zip /bar.txt                # Compress bar.txt into foo.zip\r\nzip foo.zip /bar.txt /baz.txt       # Compress bar.txt and baz.txt into foo.zip\r\nzip foo.zip /{bar,baz}.txt          # Compress bar.txt and baz.txt into foo.zip\r\nzip -r|--recurse-paths foo.zip /bar # Compress directory bar into foo.zip\r\n```\r\n\r\n### gzip\r\n\r\nCompresses a single file into *.gz files.\r\n\r\n```bash\r\ngzip /bar.txt foo.gz           # Compress bar.txt into foo.gz and then delete bar.txt\r\ngzip -k|--keep /bar.txt foo.gz # Compress bar.txt into foo.gz\r\n```\r\n\r\n### tar -c\r\n\r\nCompresses (optionally) and combines one or more files into a single *.tar, *.tar.gz, *.tpz or *.tgz file.\r\n\r\n```bash\r\ntar -c|--create -z|--gzip -f|--file=foo.tgz /bar.txt /baz.txt # Compress bar.txt and baz.txt into foo.tgz\r\ntar -c|--create -z|--gzip -f|--file=foo.tgz /{bar,baz}.txt    # Compress bar.txt and baz.txt into foo.tgz\r\ntar -c|--create -z|--gzip -f|--file=foo.tgz /bar              # Compress directory bar into foo.tgz\r\n```\r\n\r\n## Decompressing Files\r\n\r\n### unzip\r\n\r\n```bash\r\nunzip foo.zip          # Unzip foo.zip into current directory\r\n```\r\n\r\n### gunzip\r\n\r\n```bash\r\ngunzip foo.gz           # Unzip foo.gz into current directory and delete foo.gz\r\ngunzip -k|--keep foo.gz # Unzip foo.gz into current directory\r\n```\r\n\r\n### tar -x\r\n\r\n```bash\r\ntar -x|--extract -z|--gzip -f|--file=foo.tar.gz # Un-compress foo.tar.gz into current directory\r\ntar -x|--extract -f|--file=foo.tar              # Un-combine foo.tar into current directory\r\n```\r\n\r\n## Disk Usage\r\n\r\n```bash\r\ndf                     # List disks, size, used and available space\r\ndf -h|--human-readable # List disks, size, used and available space in a human readable format\r\n\r\ndu                     # List current directory, subdirectories and file sizes\r\ndu /foo/bar            # List specified directory, subdirectories and file sizes\r\ndu -h|--human-readable # List current directory, subdirectories and file sizes in a human readable format\r\ndu -d|--max-depth      # List current directory, subdirectories and file sizes within the max depth\r\ndu -d 0                # List current directory size\r\n```\r\n\r\n## Memory Usage\r\n\r\n```bash\r\nfree                   # Show memory usage\r\nfree -h|--human        # Show human readable memory usage\r\nfree -h|--human --si   # Show human readable memory usage in power of 1000 instead of 1024\r\nfree -s|--seconds 5    # Show memory usage and update continuously every five seconds\r\n```\r\n\r\n## Packages\r\n\r\n```bash\r\napt update                   # Refreshes repository index\r\napt search wget              # Search for a package\r\napt show wget                # List information about the wget package\r\napt list --all-versions wget # List all versions of the package\r\napt install wget             # Install the latest version of the wget package\r\napt install wget=1.2.3       # Install a specific version of the wget package\r\napt remove wget              # Removes the wget package\r\napt upgrade                  # Upgrades all upgradable packages\r\n```\r\n\r\n## Shutdown and Reboot\r\n\r\n```bash\r\nshutdown                     # Shutdown in 1 minute\r\nshutdown now \"Cya later\"     # Immediately shut down\r\nshutdown +5 \"Cya later\"      # Shutdown in 5 minutes\r\n\r\nshutdown --reboot            # Reboot in 1 minute\r\nshutdown -r now \"Cya later\"  # Immediately reboot\r\nshutdown -r +5 \"Cya later\"   # Reboot in 5 minutes\r\n\r\nshutdown -c                  # Cancel a shutdown or reboot\r\n\r\nreboot                       # Reboot now\r\nreboot -f                    # Force a reboot\r\n```\r\n\r\n## Identifying Processes\r\n\r\n```bash\r\ntop                    # List all processes interactively\r\nhtop                   # List all processes interactively\r\nps all                 # List all processes\r\npidof foo              # Return the PID of all foo processes\r\n\r\nCTRL+Z                 # Suspend a process running in the foreground\r\nbg                     # Resume a suspended process and run in the background\r\nfg                     # Bring the last background process to the foreground\r\nfg 1                   # Bring the background process with the PID to the foreground\r\n\r\nsleep 30 \u0026             # Sleep for 30 seconds and move the process into the background\r\njobs                   # List all background jobs\r\njobs -p                # List all background jobs with their PID\r\n\r\nlsof                   # List all open files and the process using them\r\nlsof -itcp:4000        # Return the process listening on port 4000\r\n```\r\n\r\n## Process Priority\r\n\r\nProcess priorities go from -20 (highest) to 19 (lowest).\r\n\r\n```bash\r\nnice -n -20 foo        # Change process priority by name\r\nrenice 20 PID          # Change process priority by PID\r\nps -o ni PID           # Return the process priority of PID\r\n```\r\n\r\n## Killing Processes\r\n\r\n```bash\r\nCTRL+C                 # Kill a process running in the foreground\r\nkill PID               # Shut down process by PID gracefully. Sends TERM signal.\r\nkill -9 PID            # Force shut down of process by PID. Sends SIGKILL signal.\r\npkill foo              # Shut down process by name gracefully. Sends TERM signal.\r\npkill -9 foo           # force shut down process by name. Sends SIGKILL signal.\r\nkillall foo            # Kill all process with the specified name gracefully.\r\n```\r\n\r\n## Date \u0026 Time\r\n\r\n```bash\r\ndate                   # Print the date and time\r\ndate --iso-8601        # Print the ISO8601 date\r\ndate --iso-8601=ns     # Print the ISO8601 date and time\r\n\r\ntime tree              # Time how long the tree command takes to execute\r\n```\r\n\r\n## Scheduled Tasks\r\n\r\n```pre\r\n   *      *         *         *           *\r\nMinute, Hour, Day of month, Month, Day of the week\r\n```\r\n\r\n```bash\r\ncrontab -l                 # List cron tab\r\ncrontab -e                 # Edit cron tab in Vim\r\ncrontab /path/crontab      # Load cron tab from a file\r\ncrontab -l \u003e /path/crontab # Save cron tab to a file\r\n\r\n* * * * * foo              # Run foo every minute\r\n*/15 * * * * foo           # Run foo every 15 minutes\r\n0 * * * * foo              # Run foo every hour\r\n15 6 * * * foo             # Run foo daily at 6:15 AM\r\n44 4 * * 5 foo             # Run foo every Friday at 4:44 AM\r\n0 0 1 * * foo              # Run foo at midnight on the first of the month\r\n0 0 1 1 * foo              # Run foo at midnight on the first of the year\r\n\r\nat -l                      # List scheduled tasks\r\nat -c 1                    # Show task with ID 1\r\nat -r 1                    # Remove task with ID 1\r\nat now + 2 minutes         # Create a task in Vim to execute in 2 minutes\r\nat 12:34 PM next month     # Create a task in Vim to execute at 12:34 PM next month\r\nat tomorrow                # Create a task in Vim to execute tomorrow\r\n```\r\n\r\n## HTTP Requests\r\n\r\n```bash\r\ncurl https://example.com                               # Return response body\r\ncurl -i|--include https://example.com                  # Include status code and HTTP headers\r\ncurl -L|--location https://example.com                 # Follow redirects\r\ncurl -o|--remote-name foo.txt https://example.com      # Output to a text file\r\ncurl -H|--header \"User-Agent: Foo\" https://example.com # Add a HTTP header\r\ncurl -X|--request POST -H \"Content-Type: application/json\" -d|--data '{\"foo\":\"bar\"}' https://example.com # POST JSON\r\ncurl -X POST -H --data-urlencode foo=\"bar\" http://example.com                           # POST URL Form Encoded\r\n\r\nwget https://example.com/file.txt .                            # Download a file to the current directory\r\nwget -O|--output-document foo.txt https://example.com/file.txt # Output to a file with the specified name\r\n```\r\n\r\n## Network Troubleshooting\r\n\r\n```bash\r\nping example.com            # Send multiple ping requests using the ICMP protocol\r\nping -c 10 -i 5 example.com # Make 10 attempts, 5 seconds apart\r\n\r\nip addr                     # List IP addresses on the system\r\nip route show               # Show IP addresses to router\r\n\r\nnetstat -i|--interfaces     # List all network interfaces and in/out usage\r\nnetstat -l|--listening      # List all open ports\r\n\r\ntraceroute example.com      # List all servers the network traffic goes through\r\n\r\nmtr -w|--report-wide example.com                                    # Continually list all servers the network traffic goes through\r\nmtr -r|--report -w|--report-wide -c|--report-cycles 100 example.com # Output a report that lists network traffic 100 times\r\n\r\nnmap 0.0.0.0                # Scan for the 1000 most common open ports on localhost\r\nnmap 0.0.0.0 -p1-65535      # Scan for open ports on localhost between 1 and 65535\r\nnmap 192.168.4.3            # Scan for the 1000 most common open ports on a remote IP address\r\nnmap -sP 192.168.1.1/24     # Discover all machines on the network by ping'ing them\r\n```\r\n\r\n## DNS\r\n\r\n```bash\r\nhost example.com            # Show the IPv4 and IPv6 addresses\r\n\r\ndig example.com             # Show complete DNS information\r\n\r\ncat /etc/resolv.conf        # resolv.conf lists nameservers\r\n```\r\n\r\n## Hardware\r\n\r\n```bash\r\nlsusb                  # List USB devices\r\nlspci                  # List PCI hardware\r\nlshw                   # List all hardware\r\n```\r\n\r\n## Terminal Multiplexers\r\n\r\nStart multiple terminal sessions. Active sessions persist reboots. `tmux` is more modern than `screen`.\r\n\r\n```bash\r\ntmux             # Start a new session (CTRL-b + d to detach)\r\ntmux ls          # List all sessions\r\ntmux attach -t 0 # Reattach to a session\r\n\r\nscreen           # Start a new session (CTRL-a + d to detach)\r\nscreen -ls       # List all sessions\r\nscreen -R 31166  # Reattach to a session\r\n\r\nexit             # Exit a session\r\n```\r\n\r\n## Secure Shell Protocol (SSH)\r\n\r\n```bash\r\nssh hostname                 # Connect to hostname using your current user name over the default SSH port 22\r\nssh -i foo.pem hostname      # Connect to hostname using the identity file\r\nssh user@hostname            # Connect to hostname using the user over the default SSH port 22\r\nssh user@hostname -p 8765    # Connect to hostname using the user over a custom port\r\nssh ssh://user@hostname:8765 # Connect to hostname using the user over a custom port\r\n```\r\n\r\nSet default user and port in `~/.ssh/config`, so you can just enter the name next time:\r\n\r\n```bash\r\n$ cat ~/.ssh/config\r\nHost name\r\n  User foo\r\n  Hostname 127.0.0.1\r\n  Port 8765\r\n$ ssh name\r\n```\r\n\r\n## Secure Copy\r\n\r\n```bash\r\nscp foo.txt ubuntu@hostname:/home/ubuntu # Copy foo.txt into the specified remote directory\r\n```\r\n\r\n## Bash Profile\r\n\r\n- bash - `.bashrc`\r\n- zsh - `.zshrc`\r\n\r\n```bash\r\n# Always run ls after cd\r\nfunction cd {\r\n  builtin cd \"$@\" \u0026\u0026 ls\r\n}\r\n\r\n# Prompt user before overwriting any files\r\nalias cp='cp --interactive'\r\nalias mv='mv --interactive'\r\nalias rm='rm --interactive'\r\n\r\n# Always show disk usage in a human readable format\r\nalias df='df -h'\r\nalias du='du -h'\r\n```\r\n\r\n## Bash Script\r\n\r\n### Variables\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\nfoo=123                # Initialize variable foo with 123\r\ndeclare -i foo=123     # Initialize an integer foo with 123\r\ndeclare -r foo=123     # Initialize readonly variable foo with 123\r\necho $foo              # Print variable foo\r\necho ${foo}_'bar'      # Print variable foo followed by _bar\r\necho ${foo:-'default'} # Print variable foo if it exists otherwise print default\r\n\r\nexport foo             # Make foo available to child processes\r\nunset foo              # Make foo unavailable to child processes\r\n```\r\n\r\n### Environment Variables\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\nenv            # List all environment variables\r\necho $PATH     # Print PATH environment variable\r\nexport FOO=Bar # Set an environment variable\r\n```\r\n\r\n### Functions\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\ngreet() {\r\n  local world = \"World\"\r\n  echo \"$1 $world\"\r\n  return \"$1 $world\"\r\n}\r\ngreet \"Hello\"\r\ngreeting=$(greet \"Hello\")\r\n```\r\n\r\n### Exit Codes\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\nexit 0   # Exit the script successfully\r\nexit 1   # Exit the script unsuccessfully\r\necho $?  # Print the last exit code\r\n```\r\n\r\n### Conditional Statements\r\n\r\n#### Boolean Operators\r\n\r\n- `$foo` - Is true\r\n- `!$foo` - Is false\r\n\r\n#### Numeric Operators\r\n\r\n- `-eq` - Equals\r\n- `-ne` - Not equals\r\n- `-gt` - Greater than\r\n- `-ge` - Greater than or equal to\r\n- `-lt` - Less than\r\n- `-le` - Less than or equal to\r\n- `-e` foo.txt - Check file exists\r\n- `-z` foo - Check if variable exists\r\n\r\n#### String Operators\r\n\r\n- `=` - Equals\r\n- `==` - Equals\r\n- `-z` - Is null\r\n- `-n` - Is not null\r\n- `\u003c` - Is less than in ASCII alphabetical order\r\n- `\u003e` - Is greater than in ASCII alphabetical order\r\n\r\n#### If Statements\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\nif [[$foo = 'bar']]; then\r\n  echo 'one'\r\nelif [[$foo = 'bar']] || [[$foo = 'baz']]; then\r\n  echo 'two'\r\nelif [[$foo = 'ban']] \u0026\u0026 [[$USER = 'bat']]; then\r\n  echo 'three'\r\nelse\r\n  echo 'four'\r\nfi\r\n```\r\n\r\n#### Inline If Statements\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\n[[ $USER = 'rehan' ]] \u0026\u0026 echo 'yes' || echo 'no'\r\n```\r\n\r\n#### While Loops\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\ndeclare -i counter\r\ncounter=10\r\nwhile [$counter -gt 2]; do\r\n  echo The counter is $counter\r\n  counter=counter-1\r\ndone\r\n```\r\n\r\n#### For Loops\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\nfor i in {0..10..2}\r\n  do\r\n    echo \"Index: $i\"\r\n  done\r\n\r\nfor filename in file1 file2 file3\r\n  do\r\n    echo \"Content: \" \u003e\u003e $filename\r\n  done\r\n\r\nfor filename in *;\r\n  do\r\n    echo \"Content: \" \u003e\u003e $filename\r\n  done\r\n```\r\n\r\n#### Case Statements\r\n\r\n```bash\r\n#!/bin/bash\r\n\r\necho \"What's the weather like tomorrow?\"\r\nread weather\r\n\r\ncase $weather in\r\n  sunny | warm ) echo \"Nice weather: \" $weather\r\n  ;;\r\n  cloudy | cool ) echo \"Not bad weather: \" $weather\r\n  ;;\r\n  rainy | cold ) echo \"Terrible weather: \" $weather\r\n  ;;\r\n  * ) echo \"Don't understand\"\r\n  ;;\r\nesac\r\n```\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frehansaeed%2Fbash-cheat-sheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frehansaeed%2Fbash-cheat-sheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frehansaeed%2Fbash-cheat-sheet/lists"}