0

I try to pass an argument to the function install() but the output is "add" and not my argument. I don't know how to get just the REP when i call the function directory-install(), because for know i have all the phrase "add directory...."

function install () {

    echo $1 #output not ok, show "add"

}


function directory-install () {

    read -p "enter directory " REP
    if cd $REP 2> /dev/null ; then
        echo -e "add directory '$REP'\n"
    else
        mkdir REP
        echo -e "creat directory \n"
    fi
    echo $REP
}


REP=$(directory-install)
echo $REP #output not ok too show "add directory..." but i just want the REP .
install $REP
6
  • Is the issue that you left out () after function directory-install? Commented Jun 16, 2014 at 20:57
  • @DaveYarwood make an edit of my problem Commented Jun 16, 2014 at 20:59
  • Maybe I'm missing something... but where do you actually call install? (Edit: OP edited their code) Commented Jun 16, 2014 at 21:04
  • @Mr.Llama at the end of the script Commented Jun 16, 2014 at 21:04
  • Bash functions should be either f() or function f. Commented Jun 16, 2014 at 21:06

1 Answer 1

1

Your install function is working 100% correctly, the problem is that you're passing it garbage. Garbage in, garbage out.

The real culprit is your directory-install function. When you execute REP=$(directory-install), the variable REP now contains all of the text output from directory-install, not just the final echo $REP. That means the add directory or creat directory text.

If you want directory-install to only return REP, then you need to make sure that you have no other output in the function call. Alternately, you can redirect the non-return text to STDERR where it will be displayed, but not captured.

Example:

function badExample() {
    echo "Hello World"
    echo "ReturnText"
}

rtn=$(badExample)
# rtn now contains "Hello World\nReturnText"


function goodExample() {
    echo "Hello World" 1>&2
    echo "ReturnText"
}

rtn=$(goodExample)
# "Hello World" will appear on screen and rtn contains "ReturnText"
Sign up to request clarification or add additional context in comments.

3 Comments

But if i need other output, how can i do ?
@Droïdeka - I edited the response. You can redirect the output to STDERR where it will appear on screen but not be captured in the return. The 1>&2 means "redirect STDOUT to STDERR".
very simple and effective ! Real thx for the explanations, the time, and the exemple you made !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.