简体   繁体   中英

How to use/call variables from another function in bash

I am learning to play around with functions in bash. I have the first function read_file() that reads /etc/file and replaces ':'with a space between words (eg root:x:0:0:root ... becomes root x 0 0 root ... ). I then want to be able to manipulate output from individual words in each of the lines. My second function- display__user_shell() prints our the shell for each corresponding users as is in the /etc/file.

My problem is figuring out how to call the first function read_file() and using its variables in the display__user_shell function.

I have been able to do the above when using input from a single line rather than reading from a file. i just called new_data -ie $new_data from the display__user_shell() function

read_file() {
read -p "Enter file" file
while read line
    do
        newlin=$(echo $line | tr ":" " ")
        echo newlin
    done
}
oldIFS=$IFS
IFS=" "
ct=0
display__user_shell() {
readfile
    for item in $newlin;
    do
        [ $ct -eq 0 ] && name="$item";
        [ $ct -eq 6 ] && name="$item";
    done
echo "$user's shell is $shell"
}
IFS=$oldIFS
display__user_shell

the first line of the output should be..

root's shell is /bin/bash

Irrespective of the implementation there is an interesting question here: how to reference variables from one function in another function. The short answer is that you can:

$ a() { aye=bee; }
$ b() { echo "$aye"; }
$ a
$ b
bee

But this is a very bad idea - Bash has "unfortunate" scoping rules different from safer languages like Java, Python, or Ruby, and code like this is very hard to follow. Instead there are several patterns you can use to produce more readable code:

  • Print the value in the inner function and assign that to a value in the outer function:

     a() { echo 'bee' } b() { aye="$(a)" echo "$aye" } b # Prints "bee" 
  • Call and assign to a variable the first function in the outer scope and use it in the second function:

     a() { echo 'bee' } aye="$(a)" b() { echo "$aye" } b # Prints "bee" 
  • Treat the first and second functions as a pipeline, passing standard output of the first one to the standard input of the second one ( read is a slow way to process a large file, but it'll serve as an example):

     a() { echo 'bee' } b() { while read -r line do echo "$line" done } a | b # Prints "bee" 

Which one you choose depends on things like what else you intend to do with what a returns and whether a produces huge amounts of output.

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