Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer

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.
share|improve this answer
    
I tried that but did not get an echo of the string in the method. It just shows a blank.. –  ryekayo Jun 16 at 15:48
    
You tried what, exactly? –  glenn jackman Jun 16 at 15:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.