Janek
Janek

Reputation: 61

Bash lost variables after function

I've a simple Bash script.

#!/bin/bash

function askExp
(
    read -ep "$1" -n "$2" -r "$3"
)
askExp "PHP? [Y/n]: " 1 php

echo $php

How to modify above script to work? No after echo $php I get nothing. I need to use bash function, because after that I'll add a regexp verification inside function. The function will be used many times in a script.

Upvotes: 1

Views: 870

Answers (1)

Inian
Inian

Reputation: 85895

The shell runs whatever present under (..) in a sub-shell and especially variables the defined lose their scope once the shell terminates. You needed to enclose the function within {..} which encloses a compound statement in bash shell to make sure the commands within are run in the same shell as the one invoked.

function askExp { read -ep "$1" -n "$2" -r "$3"; }

As a small experiment you can observe the output of

hw()(
  echo hello world from $BASHPID
)
hw 
echo $BASHPID

and when running from the same shell.

hw(){
  echo hello world from $BASHPID
}
hw 
echo $BASHPID

The reason is in the former case, the variable set in the shell created inside (..) is lost in the local shell.

Upvotes: 2

Related Questions