简体   繁体   中英

how to call a function within another variable which has backtick in Shell Script

I want to call a function within another variable which has back-tick. how do i make this work?

example:

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

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

count_files

You can use this :

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

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

count_files

You must set the correct execution syntax.

$(Command)

or with back-ticks

`Command`

In your example you missing that bevor the ls ... command. And you missing the first slash in your home Directory (Otherwise, it would only work from root / Directory.)

Try:

#!/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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM