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

169 天前
 JasonLaw

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}"
}
705 次点击
所在节点   Bash
4 条回复
ysc3839
169 天前
2 ,因为不依赖 bash array 特性,不需要先分割再合并,同时印象中 IFS 分割坑很多,个人会尽量避免使用。除非不允许启动新进程,否则选第二种更好。
james122333
169 天前
都很差 第一个稍微好了点 IFS 本身没问题
漂亮写法如下
function get_profile {
local arr profile IFS_old="$IFS" IFS="/"
arr=($PWD)
IFS="$IFS_old"
profile="${arr[-2]}"
echo "$profile"
}
james122333
169 天前
而且都不知道 get_profile 在做什么 也许更详细会有更好的写法
james122333
169 天前
个人觉得这函数有点鸡肋

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/997708

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX