如何在Shell脚本中具有反引号的另一个变量中调用函数

时间:2019-02-06 12:35:47

标签: linux bash shell unix sh

我想在另一个带有反引号的变量中调用一个函数。我该如何工作?

示例:

location ()
{echo "home/$1/dir"}

count_files ()
{
count=`ls $(location user1) |wc -l` 
}

count_files

2 个答案:

答案 0 :(得分:-1)

您可以使用此:

location() {
   echo "home/$1/dir"
}

count_files() {
   count=$(ls $(location user1) | wc -l)
}

count_files

答案 1 :(得分:-1)

您必须设置正确的执行语法。

$(Command)

或带有反引号

`Command`

在您的示例中,您缺少了ls ...命令。而且您在主目录中缺少第一个斜杠(否则,它只能在根/目录中工作。)

尝试:

#!/bin/bash

location () {
  echo "/home/$1/dir"
}

count_files () {

  # Get the count;
  count=$(ls $(location "$1") | wc -l);

  # Return the count value;
  echo "$count";
}

# Call function and print the count result. 
# Better you set the user here and not 'hardcoded' in a function.
echo $(count_files "user1")