JasonLaw
V2EX  ›  Bash

Bash Script 代码比较,你认为哪个更加容易理解?

By JasonLaw at 2023 年 12 月 5 日 · 2593 次点击

Version 1:

getProfile() {

  CURRENT_PATH=$(pwd)
  oldIFS="$IFS" # Save the old value of IFS
  IFS="/"       # Set IFS to the new delimiter

  # Split the string into an array of substrings
  read -ra array <<<"$CURRENT_PATH"
  IFS=oldIFS
  PROFILE=${array[-2]}
  echo "${PROFILE}"

}

Version 2:

get_profile() {
  script_dir="$(dirname "$0")"
  # https://stackoverflow.com/questions/71224944/how-to-get-the-name-of-the-grandparent-directory
  profile=$(basename -- "$(realpath -m -- "$script_dir/..")")
  echo "${profile}"
}
4 条回复
ysc3839
   1
ysc3839  
   2023 年 12 月 5 日 via Android
2 ,因为不依赖 bash array 特性,不需要先分割再合并,同时印象中 IFS 分割坑很多,个人会尽量避免使用。除非不允许启动新进程,否则选第二种更好。
james122333
   2
james122333  
   2023 年 12 月 5 日 via Android
都很差 第一个稍微好了点 IFS 本身没问题
漂亮写法如下
function get_profile {
local arr profile IFS_old="$IFS" IFS="/"
arr=($PWD)
IFS="$IFS_old"
profile="${arr[-2]}"
echo "$profile"
}
james122333
   3
james122333  
   2023 年 12 月 5 日 via Android
而且都不知道 get_profile 在做什么 也许更详细会有更好的写法
james122333
   4
james122333  
   2023 年 12 月 5 日 via Android
个人觉得这函数有点鸡肋
© 2026 V2EX · 27ms · 3.9.8.5