1

So i have this program in Shell Script its basic but what i want is to read 3 values from the stdin while i start the program and then i want to print those values but for some reason it gives an error.

Expected output:

./my_script.sh hello bye 2
hello
bye
2

my output:

./my_script.sh hello bye 2
Word1=1
meu_script.sh: line 2: read: `Word2=': not a valid identifier
hello
bye
2

Program:

#!/bin/bash
read -p "Word1=" $1 "Word2=" $2 "Num=" $3

Word1="${1}"
Word2="${2}"
Num="${3}"
echo ${1}
echo ${2}
echo ${3}

Can someone explain me whats going because i dont understand btw im fairly knew in programming in shell script

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Martim Correia
  • 483
  • 5
  • 16
  • 1
    if you're passing the values on the command line then you don't want the `read` command ... you just need `Word1=... / Word2=... / Num= ...` commands to save the command line values into variables; 'course, this then raises the question of why bother with variables if all you're going to do is `echo ${1] / ${2} / ${3}` .... ??? – markp-fuso Nov 15 '20 at 18:46
  • actually i want to do something more sofisticated but i just this simple program as an example – Martim Correia Nov 15 '20 at 19:03

3 Answers3

2

Maybe I'm oversimplifying your problem, but if you want to prompt the user for inputs and save those inputs to variables (vs. just taking them directly from the command line using $1, $2, etc.), do you just want this?

#!/bin/bash
read -p "Enter word 1: " Word1
read -p "Enter word 2: " Word2
read -p "Enter Num: " Num

echo $Word1
echo $Word2
echo $Num

Alternatively, if taking them directly from the command line is what you want, just use $1, $2, and $3:

#!/bin/bash
echo $1
echo $2
echo $3

That way, ./my_script.sh hello bye 2 prints the results you want.

Marc
  • 11,403
  • 2
  • 35
  • 45
1

I just discovered the answer

The text file should be saved with UNIX Line Feeds instead of Mac OS CR or Windows CRLF

Dharman
  • 30,962
  • 25
  • 85
  • 135
JAYTEE
  • 21
  • 1
0

As already mentioned, sometimes there might be an issue with the characters you don't see, but bash does.

I had a very similar issue, even though I worked on debian all the time (but different versions). Moreover, file that used to work, stopped working. However, the problem was solved by

 dos2unix yourscriptname.sh

See this post for more details.