V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
JasonLaw
V2EX  ›  Bash

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

  •  
  •   JasonLaw · Dec 5, 2023 · 1993 views
    This topic created in 875 days ago, the information mentioned may be changed or developed.

    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  
       Dec 5, 2023 via Android
    2 ,因为不依赖 bash array 特性,不需要先分割再合并,同时印象中 IFS 分割坑很多,个人会尽量避免使用。除非不允许启动新进程,否则选第二种更好。
    james122333
        2
    james122333  
       Dec 5, 2023 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  
       Dec 5, 2023 via Android
    而且都不知道 get_profile 在做什么 也许更详细会有更好的写法
    james122333
        4
    james122333  
       Dec 5, 2023 via Android
    个人觉得这函数有点鸡肋
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5063 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 05:38 · PVG 13:38 · LAX 22:38 · JFK 01:38
    ♥ Do have faith in what you're doing.