merge 2 frequently used commands in one

Linux

This bash tip can be useful when you frequently use two commands back-to-back. Most used commands are probably cd & ls and cp /mv and cd.

1. cd and ls in one command

Open .bashrc :

nano ~/.bashrc

Add the following function at the end:

cds() {
        cd "$@" && ls;
}

After modifying .bashrc file, we need to reload it for the changes to take effect in the current terminal session :

 . ~/.bashrc

or

 source ~/.bashrc

or close and open the terminal ; a new terminal session will automatically load the updated ~/.bashrc file.

A more robust variant, with some improvements :

  • handling of empty arguments
  • Displaying the current path after cd
cds() {

    # Check if any arguments are provided
    if [ $# -eq 0 ]; then
        echo "Error: No directory specified." >&2
        return 1
    fi

    # Change directory and display contents
    if cd "$@" 2>/dev/null; then
        echo "Current directory: $(pwd)"
        ls -l
    else
        echo "Error: Failed to change directory to '$*'." >&2
        return 1
    fi
}

Note : The newly created function should not be used in case we just need to cd and create a file for example.In large directories containing hundreds of files it will take too long (several seconds to minutes) to display contents.

2. cp and cd in one command

cpcd() {
  # Check if the first argument ($1) exists
  if [ ! -e "$1" ]; then
    echo "Error: File or directory '$1' does not exist." >&2
    return 1
  fi

  # Check if the second argument ($2) is writable
  if [ -d "$2" ]; then
    if [ ! -w "$2" ]; then
      echo "Error: Directory '$2' is not writable." >&2
      return 1
    fi
    # Copy and change directory
    if cp "$1" "$2"; then
      cd "$2" || echo "Error: Unable to change to directory '$2'." >&2
    else
      echo "Error: Failed to copy '$1' to '$2'." >&2
      return 1
    fi
  else
    # Check if the parent directory of $2 is writable (if $2 is a file)
    parent_dir=$(dirname "$2")
    if [ ! -w "$parent_dir" ]; then
      echo "Error: Parent directory '$parent_dir' is not writable." >&2
      return 1
    fi
    # Simply copy the file
    if ! cp "$1" "$2"; then
      echo "Error: Failed to copy '$1' to '$2'." >&2
      return 1
    fi
  fi
}

source : Ostechnics

Previous Post Next Post