V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
JasonLaw
V2EX  ›  Bash

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

  •  
  •   JasonLaw · 148 天前 · 679 次点击
    这是一个创建于 148 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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}"
    }
    
    ysc3839
        1
    ysc3839  
       148 天前 via Android
    2 ,因为不依赖 bash array 特性,不需要先分割再合并,同时印象中 IFS 分割坑很多,个人会尽量避免使用。除非不允许启动新进程,否则选第二种更好。
    james122333
        2
    james122333  
       148 天前 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  
       148 天前 via Android
    而且都不知道 get_profile 在做什么 也许更详细会有更好的写法
    james122333
        4
    james122333  
       148 天前 via Android
    个人觉得这函数有点鸡肋
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2276 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 12:11 · PVG 20:11 · LAX 05:11 · JFK 08:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.