Skip to content

Instantly share code, notes, and snippets.

@BMTLab
Last active April 2, 2024 10:31
Show Gist options
  • Save BMTLab/9cd8fc1070096845fc83bb972c90c631 to your computer and use it in GitHub Desktop.
Save BMTLab/9cd8fc1070096845fc83bb972c90c631 to your computer and use it in GitHub Desktop.
Combines 'cd' and 'ls' commands to change directories and immediately list their contents to speed up file system navigation
#!/bin/bash
# Author: Nikita Neverov (BMTLab)
# Version: 1.0.1
#
# cdl: Change the current working directory and list its contents (cd ... && ls -a).
# This function changes the current working directory to the specified directory
# or to $HOME if no directory is specified, and then lists the contents of the directory.
#
function cdl() {
local -r args=$1
local help_message
# Multi-line usage message
read -r -d '' help_message <<'EOF'
Usage: cdl [<directory>]
Change the current working directory to <directory> (or $HOME if not specified) and list its contents.
EOF
# Display help message if -h or --help is passed as an argument.
if [[ $args == '-h' ]] || [[ $args == '--help' ]]; then
echo "$help_message"
return 0
fi
# Set default argument as HOME if not provided
local -r dir="${1:-$HOME}"
local -r dir_not_exist_error='Error: Directory does not exist or cannot be accessed: '
# Change directory and list contents if successful
if cd "$dir" >/dev/null 2>&1; then
ls -a --color=auto
else
# Display error message if cd command fails
local -ir cd_error_code=$?
echo "${dir_not_exist_error}'$dir'" >&2
return $cd_error_code
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment