Giving a parameter and help section to shell scrip

2019-09-20 17:58发布

问题:

I have a problem that I want to determine folder name manually. For example, if user runs this script as below,

./scriptname -k 

They can take the results, but folder names are determined in script. How can I determine folder name manually as below?

回答1:

You could write the help as a function:

usage(){
cat <<EOT
Usage: ${0##*/} dir1 dir2
EOT
}

if [ $# -ne 2 ]; then
    usage
    echo 'please enter two folder names'
    exit 1
fi

if [ ! -d "$1" ]; then
    usage
    echo "$1 is not a folder"
    exit 1
fi

if [ ! -d "$2" ]; then
    usage
    echo "$2 is not a folder"
    exit 1
fi

# continue script


回答2:

#!/bin/bash

check_input_directories()
{
    if [[ ! -f "${folder1}" "${folder2}" ]]; then

        #your searching program

fi
}
Show_help()
{

cat <<_EOF
Usage  : $0 <options>        <path>
            Options:
               -f       <folder>  <folder>
_EOF
}

MAIN () {

case "$1" in
                        -f)
                                check_input_directories
                         ;;
                         *)
                                Show_help

esac

}

MAIN $*


回答3:

I deleted one untested answer yesterday and return today with this tested bash script:

#!/bin/bash

check_input_directories() {

  folder1="$1"
  folder2="$2"

  if [[ ! -d "${folder1}" && ! -d "${folder2}" ]]; then

    dir1=~/${folder1}
    dir2=~/${folder2}

    for i in $(find $dir1 -printf "%f\n")
    do
      find $dir2 -name $i -print
    done

  fi
}

Show_help() {

  cat <<_EOF
    Usage  : $0 <options>        <path>
    You can use this script as below,
    -d       folder1/ folder2/
  _EOF
}

MAIN () {
  case "$1" in
    -d)
      check_input_directories $2 $3
      ;;
    *)
      Show_help
  esac
}

MAIN $*


标签: shell unix