簡體   English   中英

如何動態更新.bashrc文件中的別名?

[英]How to dynamically update an alias in the .bashrc file?

我在部門.bashrc文件中定義別名,該別名源於單個用戶.bashrc文件之前。 在個人用戶.bashrc文件中,我希望能夠向現有別名添加選項。 因此,例如在第一個(部門) .bashrc文件中,我具有以下內容:

alias my_command = '/usr/local/bin/my_command -option1 -option2'

在用戶.bashrc文件中,我想建立在現有別名上,例如

alias my_command = 'my_command -option3'

如所寫,用戶.bashrc文件中的別名指令將僅替換部門.bashrc文件中定義的相同名稱的別名。 我嘗試通過以下方法解決此問題:

existing_alias_components=($(type my_command))

在數組的前四個元素中,它返回單詞my_command,alias和to。 我想捕獲其余的數組元素,將它們重新連接成一個字符串(例如$string ),然后發出命令

alias my_command="$string -option 3"

我面臨這樣一個挑戰:圍繞別名的第一個定義的引號字符進入前四個之后的第一個和最后一個數組值。 我可以對它們進行細分,但是要成為Perl的一線工具,需要做很多工作。 有沒有更方便的方法可以做到這一點?

謝謝!

考慮改用函數。 例如:

my_command_args=( -option1 -option2 )
my_command() {
  command my_command "${my_command_args[@]}" "$@"
}

...之后某人可以運行:

# add a 3rd option on the end:
my_command_args+=( -option-3 )

...或者在新參數之前加上:

# add a 0th option on the beginning
my_command_args=( -option0 "${my_command_args[@]}" )

這里的最大優點是您可以將數據追加到別名中,而無需安全地引用它。 例如,以下是使用別名的非常不好的消息:

# This is evil
bad_string='$(rm -rf /tmp)'
alias my_command="$oldalias --fail-if-command-contains=$bad_string"

...而是需要通過類似printf '%q'方式來運行:

# ...can make it safer this way, if using an alias
bad_string='$(rm -rf /tmp)'
printf -v bad_string_safe %q "$bad_string"
alias my_command="$oldalias --fail-if-command-contains=$bad_string_safe"

...但如果使用函數公式,則無需執行該步驟將是完全安全的:

# This is safe
bad_string='$(rm -rf /tmp)'
my_command_args+=( --fail-if-command-contains="$bad_string" )

我只是從單引號之間提取別名值:

 oldalias=$(alias my_command|sed "s/^[^']*'//; s/'$//"); 

然后做

 alias my_command="$oldalias -option 3"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM