[英]bash: whitespaces removed from string
我編寫了一個小的庫函數來幫助我在腳本所有者不是root的情況下退出:
#!/bin/bash
# Exit for non-root user
exit_if_not_root() {
if [ "$(id -u)" == "0" ]; then return; fi
if [ -n "$1" ];
then
printf "%s" "$1"
else
printf "Only root should execute This script. Exiting now.\n"
fi
exit 1
}
在這里,我從另一個文件中調用它:
#!/bin/bash
source ../bashgimp.sh
exit_if_not_root "I strike quickly, being moved. But thou art not quickly moved to strike.\n You're not root, exiting with custom message."
輸出為:
I strike quickly, being moved. But thou art not quickly moved to strike.\n You're not root, exiting with custom message.
如何使換行符正確顯示?
只需使用echo -e
而不是printf
也許取消"%s"
而只是
printf "$1"
在這種情況下將是最簡單的。
默認情況下,字符串中不對ANSI-C轉義序列進行處理-它們與其他文字相同。 表格
$'ANSI text here'
但是將進行反斜杠轉義替換。 ( 參考 )
但就您而言,由於您只是print
提供的格式化字符串,因此您最好將其視為格式化字符串而不是參數。
或正確引用字符串。 您可以在帶引號的字符串中使用文字換行符,也可以使用$'string'
引用語法。
在函數中,將行更改為
printf "%s\n" "$@"
並這樣調用函數
exit_if_not_root "text for line 1" "text for line2" "text for line 3"
printf
將重新使用格式字符串以提供盡可能多的值字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.