Linux Shell Shortcuts
Special Variables
$_
- Last argument of previous command
mkdir my_directory && cd "$_"
cp file.txt /backup && ls "$_" # ls /backup
!!
- Repeat last command
sudo !! # Run last command with sudo
echo "test" && !! # Repeat the echo
!$
- Last argument of previous command (alternative to $_
)
touch file.txt && vim !$ # vim file.txt
$?
- Exit status of last command
ls /nonexistent; echo "Exit code: $?" # Exit code: 2
Directory Navigation Shortcuts
cd -
- Go back to previous directory
cd /home/user && cd /tmp && cd - # Back to /home/user
pushd
and popd
- Directory stack
pushd /tmp # Save current dir and go to /tmp
pushd /var # Save /tmp and go to /var
popd # Back to /tmp
popd # Back to original directory
Command Shortcuts
^old^new
- Replace text in last command
echo "hello world"
^world^universe # Runs: echo "hello universe"
!command
- Run last command starting with "command"
!mk # Runs last command starting with "mk"
!?text? # Runs last command containing "text"
File Operations
Create file and open in editor
touch file.txt && vim "$_"
Copy file and edit the copy
cp config.txt backup_config.txt && vim "$_"
Create nested directories and navigate
mkdir -p project/src/components && cd "$_"
Process Management
Run command in background and get PID
sleep 100 & echo "PID: $!"
Check if command succeeded
make && echo "Build successful" || echo "Build failed"
Useful Combinations
Create script file and make executable
touch script.sh && chmod +x "$_" && vim "$_"
Download and extract
wget file.tar.gz && tar -xzf "$_"
Find and edit
find . -name "*.txt" -exec vim {} \;
Create backup before editing
cp important.conf{,.backup} && vim important.conf
Brace Expansion Tricks
Create multiple files
touch file{1..5}.txt
# Creates file1.txt through file5.txt
Create directory structure
mkdir -p project/{src,docs,tests} && cd project
Backup with timestamp
cp config.txt config.txt.$(date +%Y%m%d)
Backup file with different extension
cp reallylongfilename.txt{,.orig}
# Expands to: cp reallylongfilename.txt reallylongfilename.txt.orig
These shortcuts can significantly speed up your command-line workflow once you get used to them!