actuallyatiger
actuallyatiger

Reputation: 191

Bash mkdir and cd script returning error but still working

For a while, I've had a need for a bash script to make a directory and cd into it. Most of the solutions online work but are very minimal so I wanted to make one that handles things like creating parent directories and permission checking. Here's my code:

#!/bin/bash

function mkcd() {

  # Check for no arguments
  if "$#" -eq 0; then
    echo "Error: no arguments provided"
    return 1
  fi

  # Checks if help flag is used
  # Not with other flags to ensure the directory isn't assumed to be a flag
  if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    echo "mkcd - Makes a directory and changes directory to it\n"
    echo "Flags:"
    echo "    -h, --help           Display help message"
    echo "    -p, --parents        Makes parent directories as neeeded"
    echo "    -a, --absolute       Receive an absolute directory instead of relative\n"
    echo "Format: mkcd [arguments] directory"
    return 0
  fi

  # Flag checker
  while test "$#" -gt 1; do
    case "$1" in
    -p | --parents)
      mkcd_parents=true
      shift
      ;;
    -a | --absolute)
      shift
      ;;
    esac
  done

  mkcd_path="$1"

  if [[ ! -w "$PWD" ]]; then
    echo "Error: Permission denied"
    return 1
  fi

  if [[ -d "$mkcd_path" ]]; then
    echo "Error: Directory already exists"
    return 1
  fi

  if "$mkcd_parents"; then
    mkdir -p "$mkcd_path"
    cd "$mkcd_path"
  else
    mkdir "$mkcd_path"
    cd "$mkcd_path"
  fi
}

I also sourced it in my .zshrc file with source ~/bin/*

When I run the command, I get this output:

~ ❯ mkcd test_dir
mkcd:3: command not found: 1
mkcd:45: permission denied:
~/test_dir ❯

Does anyone understand why I'm getting this error?

Upvotes: 0

Views: 251

Answers (1)

ilkkachu
ilkkachu

Reputation: 6517

if "$#" -eq 0; then

Since you have one argument to the script, that becomes after expansions

if 1 -eq 0; then

You probably meant to do

if [[ "$#" -eq 0 ]]; then

instead. (With either of [ .. ] or [[ .. ]].)


As an aside, I would change this

if "$mkcd_parents"; then

to

if [ "$mkcd_parents" = "true" ]; then

Otherwise if the -p option isn't given, $mkcd_parents is unset, "$mkcd_parents" expands to the empty string, and you get an error about that command not being found.

Upvotes: 1

Related Questions