[英]How can Linux program, e.g. bash or python script, know how it was started: from command line or interactive GUI?
[英]Define function in unix/linux command line (e.g. BASH)
有時我會為一項特定任務重復多次,但可能永遠不會以完全相同的形式再次使用。 它包含我從目錄列表中粘貼的文件名。 介於兩者之間並創建一個 bash 腳本,我想也許我可以在命令行中創建一個單行函數,例如:
numresults(){ ls "$1"/RealignerTargetCreator | wc -l }
我嘗試了一些方法,例如使用 eval、使用numresults=function...
,但沒有偶然發現正確的語法,並且到目前為止還沒有在網上找到任何東西。 (接下來的一切都只是關於 bash 函數的教程)。
bash
中的函數本質上是命名的復合命令(或代碼塊)。 從man bash
:Compound Commands A compound command is one of the following: ... { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. ... Shell Function Definitions A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. ... [C]ommand is usually a list of commands between { and }, but may be any command listed under Compound Commands above.
沒有給出任何理由,這只是語法。
嘗試在wc -l
后使用分號:
numresults(){ ls "$1"/RealignerTargetCreator | wc -l; }
不要使用ls | wc -l
ls | wc -l
因為如果文件名中有換行符,它可能會給你錯誤的結果。 您可以改用此功能:
numresults() { find "$1" -mindepth 1 -printf '.' | wc -c; }
您也可以在沒有find
情況下計算文件。 使用數組,
numresults () { local files=( "$1"/* ); echo "${#files[@]}"; }
或使用位置參數
numresults () { set -- "$1"/*; echo "$#"; }
為了匹配隱藏文件,
numresults () { local files=( "$1"/* "$1"/.* ); echo $(("${#files[@]}" - 2)); }
numresults () { set -- "$1"/* "$1"/.*; echo $(("$#" - 2)); }
(從結果中減去 2 補償.
和..
。)
你可以得到一個
bash: syntax error near unexpected token `('
如果您已經有一個與您嘗試定義的函數同名的alias
,則會出錯。
最簡單的方法可能是呼應您想要返回的內容。
function myfunc()
{
local myresult='some value'
echo "$myresult"
}
result=$(myfunc) # or result=`myfunc`
echo $result
無論如何, 在這里您可以找到用於更高級目的的好方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.