2

I have this code snippet I am working on for a small project I am doing:

echo "Please enter SUID: ";
read $uid

uid_Assoc(){
        arg1=$1
        echo $1;
}

uid_Assoc

Now to start, I would like this to prompt for a string and read the string. From there I would like to pass that string as an argument and echo it out. But I am not sure how to pass the string off as a parameter. When I attempt to do something like:

uid_Assoc($uid)

It throws a syntax error (I figured that would be incorrect anyways). Are there any suggestions on how to do this?

UPDATE: I also tried re-arranging the code a bit to look like this:

function uid_Assoc(){
        arg1=$1
        echo $1;
}
echo "Please enter SUID: ";
read $uid
uid_Assoc $uid

But that didn't seem to work either.

2 Answers 2

4

The read command takes a variable name, so remove the sigil:

read uid

What you are doing, is this: sending the contents of the uid variable as the variable name for the read command. Since this value is currently empty, you have

echo "a prompt: "
read

That is valid bash code. The default variable name for a "bald" read command is REPLY

Given your code, here is a mild rewrite:

function uid_Assoc {
        local arg1=$1
        echo "$arg1";
}

read -p "Please enter SUID: " uid
uid_Assoc "$uid"

Notes:

  • you don't need both the function keyword and the () syntax, choose one or the other (my opinion only)
  • localize variables in functions to limit their scope
  • use the -p option to read
  • always quote referenced variables (you never know how many spaces the user will type), unless you know why you need to leave a variable unquoted.
2
  • I tried that but did not get an echo of the string in the method. It just shows a blank..
    – ryekayo
    Jun 16, 2014 at 15:48
  • You tried what, exactly? Jun 16, 2014 at 15:50
3

Modify your script as follow:

#!/bin/bash

echo "Please enter SUID: ";
read uid

uid_Assoc () {
        arg1="$1"
        echo "$1"
        echo "$arg1"
}

uid_Assoc "$uid"

You just need to remove the $ prefix before uid in the read call.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .