如何解析 shell 函数中的选项以导航多个项目

如何解析 shell 函数中的选项以导航多个项目

我可以使用有关我正在尝试编写的 bash 的帮助。脚本的目的是在处理多个项目时加快我的开发速度。我在代码中标记了我有疑问的部分。

# is there a way to persist this through working enviornments besides this?
declare -x WORKING=`cat ~/.working`

#alias p='builtin cd $WORKING && pwd && ls'
alias pj='builtin cd $WORKING/public/javascripts && pwd && ls'

function pp {
echo `pwd` > ~/.working
}


# is there a way to close the scope of this function?
function p {

  # how do I process flags here?
  # -f and -d etc. can exist but may not
  # either way I want $1 to be set to the first string if there
  # is one


  if [ -z "$1" ]
  then
    echo '*'
    builtin cd $WORKING && pwd && ls
    return
  fi



  BACK=`pwd`
  builtin cd $WORKING

  #f=`find . -iname "$1"`
  f=( `echo $(find . -type d -o -type f -iname "$1") | grep -v -E "git|node"` )
  #echo ${f[1]}

  if [ -z "${f[0]}" ]
  then
    return
  fi


  if [ -z "${f[1]}" ]
  then
    # how can I write this as a switch?
    if [ -f ${f[0]} ]
    then
      vim ${f[0]}
      return
    fi
    if [ -d ${f[0]} ]
    then
      builtin cd ${f[0]}
      return
    fi
  else
    echo "multiple found"
  #for path in $f
  #do
  # sort files and dirs
  #  sort dirs by path
  #  sort files by path
    #done

  #  display dirs one color
  #  display files another color
  #     offer choices
  #     1) open all files
  #     2) open a file
  #     3) cd to selected directory
  #     4) do nothing

  fi


 # nothing found
 builtin $BACK
}

答案1

# is there a way to persist this through working enviornments besides this?
declare -x WORKING=`cat ~/.working`

也许使用:

export WORKING=$(cat ~/.working)

这应该将其添加到您的环境中直到重新启动。

您稍后应该可以通过使用来引用此内容

echo $WORKING

从提示。

答案2

对于变量持久性,您需要一种非主内存的机制。文件是一个不错的选择。这里我使用 bash 快捷方式$(cat filename)

declare -x WORKING=$(< ~/.working)

你不需要echo $(pwd),只需pwd

function pp { pwd > ~/.working; } 

通过“关闭范围”,我假设您的意思是将局部变量保留在函数的本地:使用local内置函数

function p {

  local OPTIND OPTARG
  local optstring=':fd'  # declare other options here: see "help getopts"
  local has_f=false has_d=false

  while getopts $optstring option; do
    case $option in
      f) has_f=true ;;
      d) has_d=true ;;
      ?) echo "invalid option: -$OPTARG"; return 1 ;;
    esac
  done
  shift $((OPTIND - 1))

  if $has_f ; then
    do something if -f

  elif $has_d ; then
    do something if -d
  fi

  # ... whatever else you have to do ...
}

相关内容