将 bash 转换为 zsh:声明函数和 if 语句

将 bash 转换为 zsh:声明函数和 if 语句

我从某处复制了此代码,并尝试根据自己的需要对其进行修改。它是为 设计的,bash但我在 下运行它zsh

我总是无法在 zsh 下运行 bash 脚本,因为这两种语言之间似乎存在很多差异(?)。有人能告诉我我需要在这里修改什么才能让它正常工作吗zsh

declare -a files=(
  "$HOME/.dotfiles/bash/exports" # Exports
  "$HOME/.dotfiles/bash/aliases" # Aliases
  "$HOME/.dotfiles/bash/functions" # Functions
  "$HOME/.z.sh" # z binary from https://github.com/rupa/z
  "$NVM_HOME/nvm.sh" # NVM
  "$ZSH/oh-my-zsh.sh"
)

# If these files are readable, source them
for index in ${!files[*]}
do
  if [ -r ${files[$index]} ]; then
    source ${files[$index]}
  fi
done

unset files

答案1

以下是提供~/.zshrc了一堆其他文件:

# Load the zsh files. 
# This is taken from Frank Terbeck's ZSH setup.
for rc in ~/.zshrc.d/???-*.z; do
    if [[ -r ${rc} ]] ; then
        zprintf 1 "zshrc: loading %s\n" "$rc"
        source "$rc"
    else    
        zprintf 0 "zshrc: could not load %s\n" "$rc"
    fi      
done    
unset rc

这将包含以 3 位数字开头的文件名的文件(例如source)。~/.zshrc.d/421-Name.zsh

此方法的优点是允许您拥有一个~/.zshrc.d/包含所有启动脚本的目录 ( )。然后,您可以在该目录中添加/删除文件,而无需接触多个文件(您不必在~/.zshrc每次添加脚本时进行编辑)。

要更改文件名,请编辑此行:

for rc in ~/.zshrc.d/???-*.z; do

它正在搜索的目录是~/.zshrd.d/。如果您不想要 3 位数字前缀,请删除???-。扩展名 ( .z) 也可以在此处更改。

注意:?实际上并不匹配digit,这是我的错误。来自man zshexpn

?      Matches any character.

答案2

我对 bash 比 zsh 更熟悉,但这应该可以在以下任一情况下起作用:

# zsh's declare (/typeset) command doesn't allow arrays to be assigned as
# they're declared. Actually, arrays don't really have to be declared, you can
# just create them by assigning an array value; but for completeness...
declare -a files
# Comments aren't recognized inside an array declaration, so leave them out
files=(
    "$HOME/.dotfiles/bash/exports"
    "$HOME/.dotfiles/bash/aliases"
    "$HOME/.dotfiles/bash/functions"
    "$HOME/.z.sh"
    "$NVM_HOME/nvm.sh"
    "$ZSH/oh-my-zsh.sh"
)

# If these files are readable, source them
# Note: rather than iterating over a list of array indexes and using them to
# pull out the array elements, I've switched this to iterating over the array
# elements directly. It's simpler, and works the same in both bash and zsh.
for file in "${files[@]}"
do
    if [ -r "$file" ]; then
        # Note that if any of the files have bashisms, they may break in zsh
        source "$file"
    fi
done

unset files

相关内容