Меню

Ambiguous redirect bash ошибка

The following line in my Bash script

 echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  ${OUPUT_RESULTS}

gives me this error:

 line 46: ${OUPUT_RESULTS}: ambiguous redirect

Why?

doubleDown's user avatar

doubleDown

7,8181 gold badge32 silver badges48 bronze badges

asked Mar 17, 2010 at 13:08

Open the way's user avatar

Open the wayOpen the way

25.3k49 gold badges141 silver badges195 bronze badges

3

Bash can be pretty obtuse sometimes.

The following commands all return different error messages for basically the same error:

$ echo hello >
bash: syntax error near unexpected token `newline`

$ echo hello > ${NONEXISTENT}
bash: ${NONEXISTENT}: ambiguous redirect

$ echo hello > "${NONEXISTENT}"
bash: : No such file or directory

Adding quotes around the variable seems to be a good way to deal with the «ambiguous redirect» message: You tend to get a better message when you’ve made a typing mistake — and when the error is due to spaces in the filename, using quotes is the fix.

Alireza Fallah's user avatar

answered Oct 15, 2011 at 5:03

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

49.6k17 gold badges146 silver badges169 bronze badges

3

Do you have a variable named OUPUT_RESULTS or is it the more likely OUTPUT_RESULTS?


michael@isolde:~/junk$ ABC=junk.txt
michael@isolde:~/junk$ echo "Booger" > $ABC
michael@isolde:~/junk$ echo "Booger" >> $ABB
bash: $ABB: ambiguous redirect
michael@isolde:~/junk$ 

answered Mar 17, 2010 at 13:13

JUST MY correct OPINION's user avatar

2

put quotes around your variable. If it happens to have spaces, it will give you «ambiguous redirect» as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file with spaces
aaaa     dddd         mol_tag

answered Mar 17, 2010 at 13:14

ghostdog74's user avatar

ghostdog74ghostdog74

320k56 gold badges255 silver badges342 bronze badges

2

I’ve recently found that blanks in the name of the redirect file will cause the «ambiguous redirect» message.

For example if you redirect to application$(date +%Y%m%d%k%M%S).log and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log it would succeed. This is because the %k format yields ' 9' for 9AM where %H yields '09' for 9AM.

echo $(date +%Y%m%d%k%M%S) gives 20140626 95138

echo $(date +%Y%m%d%H%M%S) gives 20140626095138

The erroneous date might give something like:

echo "a" > myapp20140626 95138.log

where the following is what would be desired:

echo "a" > myapp20140626095138.log

adam_0's user avatar

adam_0

6,7006 gold badges39 silver badges52 bronze badges

answered Jun 26, 2014 at 15:01

AixNPanes's user avatar

1

Does the path specified in ${OUPUT_RESULTS} contain any whitespace characters? If so, you may want to consider using ... >> "${OUPUT_RESULTS}" (using quotes).

(You may also want to consider renaming your variable to ${OUTPUT_RESULTS})

answered Mar 17, 2010 at 13:13

Thomas's user avatar

ThomasThomas

16.8k4 gold badges45 silver badges70 bronze badges

0

If your script’s redirect contains a variable, and the script body defines that variable in a section enclosed by parenthesis, you will get the «ambiguous redirect» error. Here’s a reproducible example:

  1. vim a.sh to create the script
  2. edit script to contain (logit="/home/ubuntu/test.log" && echo "a") >> ${logit}
  3. chmod +x a.sh to make it executable
  4. a.sh

If you do this, you will get «/home/ubuntu/a.sh: line 1: $logit: ambiguous redirect». This is because

«Placing a list of commands between parentheses causes a subshell to
be created, and each of the commands in list to be executed in that
subshell, without removing non-exported variables. Since the list is
executed in a subshell, variable assignments do not remain in effect
after the subshell completes.»

From Using parenthesis to group and expand expressions

To correct this, you can modify the script in step 2 to define the variable outside the parenthesis: logit="/home/ubuntu/test.log" && (echo "a") >> $logit

answered Apr 15, 2019 at 20:58

enharmonic's user avatar

enharmonicenharmonic

1,54514 silver badges28 bronze badges

If you are here trying to debug this «ambiguous redirect» error with GitHub Actions. I highly suggest trying it this way:

echo "MY_VAR=foobar" >> $GITHUB_ENV

The behavior I experienced with $GITHUB_ENV is that, it adds it to the pipeline environment variables as my example shows MY_VAR

answered Jul 6, 2022 at 11:58

Steven Kotwal's user avatar

2

I just had this error in a bash script. The issue was an accidental at the end of the previous line that was giving an error.

answered Apr 13, 2017 at 3:14

Wayne Workman's user avatar

One other thing that can cause «ambiguous redirect» is t n r in the variable name you are writing too

Maybe not nr? But err on the side of caution

Try this

echo "a" > ${output_name//[$'tnr']}

I got hit with this one while parsing HTML, Tabs t at the beginning of the line.

Nakilon's user avatar

Nakilon

34.5k14 gold badges106 silver badges139 bronze badges

answered Nov 30, 2016 at 19:51

Jim's user avatar

1

This might be the case too.

you have not specified the file in a variable and redirecting output to it, then bash will throw this error.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

out_file variable is not set up correctly so keep an eye on this too.
BTW this code is printing all the content and its filename on the console.

answered Jan 8, 2020 at 8:54

Rahul Rajput's user avatar

1

I got this error when trying to use brace expansion to write output to multiple files.

for example: echo "text" > {f1,f2}.txt results in -bash: {f1,f2}.txt: ambiguous redirect

In this case, use tee to output to multiple files:

echo "text" | tee {f1,f2,...,fn}.txt 1>/dev/null

the 1>/dev/null will prevent the text from being written to stdout

If you want to append to the file(s) use tee -a

answered Apr 28, 2020 at 15:43

spectrum's user avatar

spectrumspectrum

3593 silver badges11 bronze badges

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then (‘shell command within quotes’ + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

Ganesa Vijayakumar's user avatar

answered Oct 20, 2019 at 2:41

Anusree's user avatar

AnusreeAnusree

1461 silver badge4 bronze badges

In my case, this was a helpful warning, because the target variable (not the file) was misspelled and did not exist.

echo "ja" >> $doesNotExist

resulting in

./howdy.sh: line 4: $doesNotExist: ambiguous redirect

answered Mar 14, 2021 at 11:30

Frank N's user avatar

Frank NFrank N

9,2684 gold badges76 silver badges107 bronze badges

For my case, if I specify the output file via a env (e.g $ENV_OF_LOG_FILE), then will get the error ambiguous redirect.

But, if I use plain text as file path (e.g /path/to/log_file), then there is no error.

answered Oct 31, 2022 at 21:14

Eric's user avatar

EricEric

20.9k18 gold badges143 silver badges184 bronze badges

The following line in my Bash script

 echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  ${OUPUT_RESULTS}

gives me this error:

 line 46: ${OUPUT_RESULTS}: ambiguous redirect

Why?

doubleDown's user avatar

doubleDown

7,8181 gold badge32 silver badges48 bronze badges

asked Mar 17, 2010 at 13:08

Open the way's user avatar

Open the wayOpen the way

25.3k49 gold badges141 silver badges195 bronze badges

3

Bash can be pretty obtuse sometimes.

The following commands all return different error messages for basically the same error:

$ echo hello >
bash: syntax error near unexpected token `newline`

$ echo hello > ${NONEXISTENT}
bash: ${NONEXISTENT}: ambiguous redirect

$ echo hello > "${NONEXISTENT}"
bash: : No such file or directory

Adding quotes around the variable seems to be a good way to deal with the «ambiguous redirect» message: You tend to get a better message when you’ve made a typing mistake — and when the error is due to spaces in the filename, using quotes is the fix.

Alireza Fallah's user avatar

answered Oct 15, 2011 at 5:03

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

49.6k17 gold badges146 silver badges169 bronze badges

3

Do you have a variable named OUPUT_RESULTS or is it the more likely OUTPUT_RESULTS?


michael@isolde:~/junk$ ABC=junk.txt
michael@isolde:~/junk$ echo "Booger" > $ABC
michael@isolde:~/junk$ echo "Booger" >> $ABB
bash: $ABB: ambiguous redirect
michael@isolde:~/junk$ 

answered Mar 17, 2010 at 13:13

JUST MY correct OPINION's user avatar

2

put quotes around your variable. If it happens to have spaces, it will give you «ambiguous redirect» as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file with spaces
aaaa     dddd         mol_tag

answered Mar 17, 2010 at 13:14

ghostdog74's user avatar

ghostdog74ghostdog74

320k56 gold badges255 silver badges342 bronze badges

2

I’ve recently found that blanks in the name of the redirect file will cause the «ambiguous redirect» message.

For example if you redirect to application$(date +%Y%m%d%k%M%S).log and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log it would succeed. This is because the %k format yields ' 9' for 9AM where %H yields '09' for 9AM.

echo $(date +%Y%m%d%k%M%S) gives 20140626 95138

echo $(date +%Y%m%d%H%M%S) gives 20140626095138

The erroneous date might give something like:

echo "a" > myapp20140626 95138.log

where the following is what would be desired:

echo "a" > myapp20140626095138.log

adam_0's user avatar

adam_0

6,7006 gold badges39 silver badges52 bronze badges

answered Jun 26, 2014 at 15:01

AixNPanes's user avatar

1

Does the path specified in ${OUPUT_RESULTS} contain any whitespace characters? If so, you may want to consider using ... >> "${OUPUT_RESULTS}" (using quotes).

(You may also want to consider renaming your variable to ${OUTPUT_RESULTS})

answered Mar 17, 2010 at 13:13

Thomas's user avatar

ThomasThomas

16.8k4 gold badges45 silver badges70 bronze badges

0

If your script’s redirect contains a variable, and the script body defines that variable in a section enclosed by parenthesis, you will get the «ambiguous redirect» error. Here’s a reproducible example:

  1. vim a.sh to create the script
  2. edit script to contain (logit="/home/ubuntu/test.log" && echo "a") >> ${logit}
  3. chmod +x a.sh to make it executable
  4. a.sh

If you do this, you will get «/home/ubuntu/a.sh: line 1: $logit: ambiguous redirect». This is because

«Placing a list of commands between parentheses causes a subshell to
be created, and each of the commands in list to be executed in that
subshell, without removing non-exported variables. Since the list is
executed in a subshell, variable assignments do not remain in effect
after the subshell completes.»

From Using parenthesis to group and expand expressions

To correct this, you can modify the script in step 2 to define the variable outside the parenthesis: logit="/home/ubuntu/test.log" && (echo "a") >> $logit

answered Apr 15, 2019 at 20:58

enharmonic's user avatar

enharmonicenharmonic

1,54514 silver badges28 bronze badges

If you are here trying to debug this «ambiguous redirect» error with GitHub Actions. I highly suggest trying it this way:

echo "MY_VAR=foobar" >> $GITHUB_ENV

The behavior I experienced with $GITHUB_ENV is that, it adds it to the pipeline environment variables as my example shows MY_VAR

answered Jul 6, 2022 at 11:58

Steven Kotwal's user avatar

2

I just had this error in a bash script. The issue was an accidental at the end of the previous line that was giving an error.

answered Apr 13, 2017 at 3:14

Wayne Workman's user avatar

One other thing that can cause «ambiguous redirect» is t n r in the variable name you are writing too

Maybe not nr? But err on the side of caution

Try this

echo "a" > ${output_name//[$'tnr']}

I got hit with this one while parsing HTML, Tabs t at the beginning of the line.

Nakilon's user avatar

Nakilon

34.5k14 gold badges106 silver badges139 bronze badges

answered Nov 30, 2016 at 19:51

Jim's user avatar

1

This might be the case too.

you have not specified the file in a variable and redirecting output to it, then bash will throw this error.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

out_file variable is not set up correctly so keep an eye on this too.
BTW this code is printing all the content and its filename on the console.

answered Jan 8, 2020 at 8:54

Rahul Rajput's user avatar

1

I got this error when trying to use brace expansion to write output to multiple files.

for example: echo "text" > {f1,f2}.txt results in -bash: {f1,f2}.txt: ambiguous redirect

In this case, use tee to output to multiple files:

echo "text" | tee {f1,f2,...,fn}.txt 1>/dev/null

the 1>/dev/null will prevent the text from being written to stdout

If you want to append to the file(s) use tee -a

answered Apr 28, 2020 at 15:43

spectrum's user avatar

spectrumspectrum

3593 silver badges11 bronze badges

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then (‘shell command within quotes’ + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

Ganesa Vijayakumar's user avatar

answered Oct 20, 2019 at 2:41

Anusree's user avatar

AnusreeAnusree

1461 silver badge4 bronze badges

In my case, this was a helpful warning, because the target variable (not the file) was misspelled and did not exist.

echo "ja" >> $doesNotExist

resulting in

./howdy.sh: line 4: $doesNotExist: ambiguous redirect

answered Mar 14, 2021 at 11:30

Frank N's user avatar

Frank NFrank N

9,2684 gold badges76 silver badges107 bronze badges

For my case, if I specify the output file via a env (e.g $ENV_OF_LOG_FILE), then will get the error ambiguous redirect.

But, if I use plain text as file path (e.g /path/to/log_file), then there is no error.

answered Oct 31, 2022 at 21:14

Eric's user avatar

EricEric

20.9k18 gold badges143 silver badges184 bronze badges

The following line in my Bash script

 echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  ${OUPUT_RESULTS}

gives me this error:

 line 46: ${OUPUT_RESULTS}: ambiguous redirect

Why?

doubleDown's user avatar

doubleDown

7,8181 gold badge32 silver badges48 bronze badges

asked Mar 17, 2010 at 13:08

Open the way's user avatar

Open the wayOpen the way

25.3k49 gold badges141 silver badges195 bronze badges

3

Bash can be pretty obtuse sometimes.

The following commands all return different error messages for basically the same error:

$ echo hello >
bash: syntax error near unexpected token `newline`

$ echo hello > ${NONEXISTENT}
bash: ${NONEXISTENT}: ambiguous redirect

$ echo hello > "${NONEXISTENT}"
bash: : No such file or directory

Adding quotes around the variable seems to be a good way to deal with the «ambiguous redirect» message: You tend to get a better message when you’ve made a typing mistake — and when the error is due to spaces in the filename, using quotes is the fix.

Alireza Fallah's user avatar

answered Oct 15, 2011 at 5:03

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

49.6k17 gold badges146 silver badges169 bronze badges

3

Do you have a variable named OUPUT_RESULTS or is it the more likely OUTPUT_RESULTS?


michael@isolde:~/junk$ ABC=junk.txt
michael@isolde:~/junk$ echo "Booger" > $ABC
michael@isolde:~/junk$ echo "Booger" >> $ABB
bash: $ABB: ambiguous redirect
michael@isolde:~/junk$ 

answered Mar 17, 2010 at 13:13

JUST MY correct OPINION's user avatar

2

put quotes around your variable. If it happens to have spaces, it will give you «ambiguous redirect» as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file with spaces
aaaa     dddd         mol_tag

answered Mar 17, 2010 at 13:14

ghostdog74's user avatar

ghostdog74ghostdog74

320k56 gold badges255 silver badges342 bronze badges

2

I’ve recently found that blanks in the name of the redirect file will cause the «ambiguous redirect» message.

For example if you redirect to application$(date +%Y%m%d%k%M%S).log and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log it would succeed. This is because the %k format yields ' 9' for 9AM where %H yields '09' for 9AM.

echo $(date +%Y%m%d%k%M%S) gives 20140626 95138

echo $(date +%Y%m%d%H%M%S) gives 20140626095138

The erroneous date might give something like:

echo "a" > myapp20140626 95138.log

where the following is what would be desired:

echo "a" > myapp20140626095138.log

adam_0's user avatar

adam_0

6,7006 gold badges39 silver badges52 bronze badges

answered Jun 26, 2014 at 15:01

AixNPanes's user avatar

1

Does the path specified in ${OUPUT_RESULTS} contain any whitespace characters? If so, you may want to consider using ... >> "${OUPUT_RESULTS}" (using quotes).

(You may also want to consider renaming your variable to ${OUTPUT_RESULTS})

answered Mar 17, 2010 at 13:13

Thomas's user avatar

ThomasThomas

16.8k4 gold badges45 silver badges70 bronze badges

0

If your script’s redirect contains a variable, and the script body defines that variable in a section enclosed by parenthesis, you will get the «ambiguous redirect» error. Here’s a reproducible example:

  1. vim a.sh to create the script
  2. edit script to contain (logit="/home/ubuntu/test.log" && echo "a") >> ${logit}
  3. chmod +x a.sh to make it executable
  4. a.sh

If you do this, you will get «/home/ubuntu/a.sh: line 1: $logit: ambiguous redirect». This is because

«Placing a list of commands between parentheses causes a subshell to
be created, and each of the commands in list to be executed in that
subshell, without removing non-exported variables. Since the list is
executed in a subshell, variable assignments do not remain in effect
after the subshell completes.»

From Using parenthesis to group and expand expressions

To correct this, you can modify the script in step 2 to define the variable outside the parenthesis: logit="/home/ubuntu/test.log" && (echo "a") >> $logit

answered Apr 15, 2019 at 20:58

enharmonic's user avatar

enharmonicenharmonic

1,54514 silver badges28 bronze badges

If you are here trying to debug this «ambiguous redirect» error with GitHub Actions. I highly suggest trying it this way:

echo "MY_VAR=foobar" >> $GITHUB_ENV

The behavior I experienced with $GITHUB_ENV is that, it adds it to the pipeline environment variables as my example shows MY_VAR

answered Jul 6, 2022 at 11:58

Steven Kotwal's user avatar

2

I just had this error in a bash script. The issue was an accidental at the end of the previous line that was giving an error.

answered Apr 13, 2017 at 3:14

Wayne Workman's user avatar

One other thing that can cause «ambiguous redirect» is t n r in the variable name you are writing too

Maybe not nr? But err on the side of caution

Try this

echo "a" > ${output_name//[$'tnr']}

I got hit with this one while parsing HTML, Tabs t at the beginning of the line.

Nakilon's user avatar

Nakilon

34.5k14 gold badges106 silver badges139 bronze badges

answered Nov 30, 2016 at 19:51

Jim's user avatar

1

This might be the case too.

you have not specified the file in a variable and redirecting output to it, then bash will throw this error.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

out_file variable is not set up correctly so keep an eye on this too.
BTW this code is printing all the content and its filename on the console.

answered Jan 8, 2020 at 8:54

Rahul Rajput's user avatar

1

I got this error when trying to use brace expansion to write output to multiple files.

for example: echo "text" > {f1,f2}.txt results in -bash: {f1,f2}.txt: ambiguous redirect

In this case, use tee to output to multiple files:

echo "text" | tee {f1,f2,...,fn}.txt 1>/dev/null

the 1>/dev/null will prevent the text from being written to stdout

If you want to append to the file(s) use tee -a

answered Apr 28, 2020 at 15:43

spectrum's user avatar

spectrumspectrum

3593 silver badges11 bronze badges

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then (‘shell command within quotes’ + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

Ganesa Vijayakumar's user avatar

answered Oct 20, 2019 at 2:41

Anusree's user avatar

AnusreeAnusree

1461 silver badge4 bronze badges

In my case, this was a helpful warning, because the target variable (not the file) was misspelled and did not exist.

echo "ja" >> $doesNotExist

resulting in

./howdy.sh: line 4: $doesNotExist: ambiguous redirect

answered Mar 14, 2021 at 11:30

Frank N's user avatar

Frank NFrank N

9,2684 gold badges76 silver badges107 bronze badges

For my case, if I specify the output file via a env (e.g $ENV_OF_LOG_FILE), then will get the error ambiguous redirect.

But, if I use plain text as file path (e.g /path/to/log_file), then there is no error.

answered Oct 31, 2022 at 21:14

Eric's user avatar

EricEric

20.9k18 gold badges143 silver badges184 bronze badges

The second entry should work fine. The «ambiguous redirect» error sometimes happens if you either have spaces where they shouldn’t be, or conversely when an important space is missing.

I would simplify your command to demonstrate:

echo "Test" >/tmp/x.txt 2>&1 &

The «>/tmp/x.txt» part will redirect stdout (file handle #1). A space between the > and the file name is permitted (although in this context would be confusing), but otherwise there should not be any spaces in here.

The 2>&1 will redirect stderr (file handle 2) to whatever file handle 1 goes to (which is stdout). There must not be any spaces in here, either.

The & will background your task. This must be offset with a space from the preceding character.

Reversing the two redirections does not work (although echo is a poor choice here since it does not produce stderr output):

echo "This will not work" 2>&1 >/tmp/x.txt &

This means:

2>&1

Redirect file handle 2 to where file handle 1 goes (which at this point is still the console)

>/tmp/x.txt

Redirect file handle 1 to a file — but since file handle 2 (stderr) is already redirected at this point, it will keep its destination and still go to the console.

The first command you wrote is simply a syntax error.

echo &>/tmp/x.txt

Update: @Wildcard pointed out in the comments that this is actually valid syntax.

Следующая строка в моем сценарии Bash

 echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  ${OUPUT_RESULTS}

Дает мне эту ошибку:

 line 46: ${OUPUT_RESULTS}: ambiguous redirect

Зачем?

13 ответов

Лучший ответ

Иногда Bash может быть довольно тупым.

Все следующие команды возвращают разные сообщения об ошибках в основном для одной и той же ошибки:

$ echo hello >
bash: syntax error near unexpected token `newline`

$ echo hello > ${NONEXISTENT}
bash: ${NONEXISTENT}: ambiguous redirect

$ echo hello > "${NONEXISTENT}"
bash: : No such file or directory

Добавление кавычек вокруг переменной кажется хорошим способом справиться с сообщением о «неоднозначном перенаправлении»: вы, как правило, получите лучшее сообщение, когда допустили опечатку — и когда ошибка возникла из-за пробелов в имя файла в кавычках — это исправление.


330

Alireza Fallah
30 Авг 2014 в 10:52

У меня только что была эта ошибка в сценарии bash. Проблема заключалась в случайном в конце предыдущей строки, которая давала ошибку.


1

Wayne Workman
13 Апр 2017 в 06:14

Еще одна вещь, которая может вызвать «неоднозначное перенаправление», — это t n r в имени переменной, которое вы тоже пишете.

Может, нет nr? Но заблуждайтесь на стороне осторожности

Попробуй это

echo "a" > ${output_name//[$'tnr']}

Я столкнулся с этим при разборе HTML, вкладки t в начале строки.


1

Nakilon
15 Май 2017 в 20:17

Если перенаправление вашего скрипта содержит переменную, и тело скрипта определяет эту переменную в разделе, заключенном в круглые скобки, вы получите ошибку «неоднозначное перенаправление». Вот воспроизводимый пример:

  1. vim a.sh для создания сценария
  2. редактировать скрипт, чтобы он содержал (logit="/home/ubuntu/test.log" && echo "a") >> ${logit}
  3. chmod +x a.sh, чтобы сделать его исполняемым
  4. a.sh

Если вы сделаете это, вы получите «/home/ubuntu/a.sh: строка 1: $ logit: неоднозначное перенаправление». Это потому что

«Размещение списка команд в круглых скобках приводит к созданию подоболочки, и каждая из команд в списке будет выполняться в этой подоболочке без удаления неэкспортированных переменных. Поскольку список выполняется в подоболочке, присвоения переменных не сохраняются действует после завершения подоболочки «.

Из Использование скобок для группировки и раскрытия выражений

Чтобы исправить это, вы можете изменить сценарий на шаге 2, чтобы определить переменную вне скобок: logit="/home/ubuntu/test.log" && (echo "a") >> $logit


1

enharmonic
15 Апр 2019 в 23:58

Это тоже может быть так.

Вы не указали файл в переменной и не перенаправили на него вывод, тогда bash выдаст эту ошибку.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

Переменная out_file настроена неправильно, следите за этим. Кстати, этот код печатает весь контент и его имя на консоли.


1

Rahul Rajput
8 Янв 2020 в 11:54

Я получил эту ошибку при попытке использовать расширение скобок для записи вывода в несколько файлов.

Например: echo "text" > {f1,f2}.txt приводит к -bash: {f1,f2}.txt: ambiguous redirect

В этом случае используйте tee для вывода в несколько файлов:

echo "text" | tee {f1,f2,...,fn}.txt 1>/dev/null

1>/dev/null предотвратит запись текста в stdout

Если вы хотите добавить файл (ы), используйте tee -a


1

spectrum
28 Апр 2020 в 18:49

Если вы используете имя переменной в команде оболочки, вы должны объединить его со знаком +.

Например :

Если у вас есть два файла, и вы не собираетесь жестко кодировать имя файла, вместо этого вы хотите использовать имя переменной
"input.txt" = x
"output.txt" = y

then (‘команда оболочки в кавычках’ + x> + y)

Он будет работать таким образом, особенно если вы используете это внутри программы python с командой os.system, вероятно


0

Ganesa Vijayakumar
20 Окт 2019 в 16:47

У вас есть переменная с именем OUPUT_RESULTS или это более вероятно OUTPUT_RESULTS?


michael@isolde:~/junk$ ABC=junk.txt
michael@isolde:~/junk$ echo "Booger" > $ABC
michael@isolde:~/junk$ echo "Booger" >> $ABB
bash: $ABB: ambiguous redirect
michael@isolde:~/junk$ 


32

JUST MY correct OPINION
17 Мар 2010 в 16:13

Заключите переменную в кавычки. Если в нем есть пробелы, это также даст вам «неоднозначное перенаправление». также проверьте свою орфографию

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

Например, о неоднозначном перенаправлении

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file with spaces
aaaa     dddd         mol_tag


17

ghostdog74
17 Мар 2010 в 16:26

Недавно я обнаружил, что пробелы в имени файла перенаправления вызывают сообщение «неоднозначное перенаправление».

Например, если вы перенаправляете на application$(date +%Y%m%d%k%M%S).log и указываете неправильные символы форматирования, перенаправление не удастся, например, до 10 утра. Если, однако, вы использовали application$(date +%Y%m%d%H%M%S).log, все получилось. Это связано с тем, что формат %k дает ' 9' для 9 утра, где %H дает '09' для 9 утра.

echo $(date +%Y%m%d%k%M%S) дает 20140626 95138

echo $(date +%Y%m%d%H%M%S) дает 20140626095138

Ошибочная дата может дать что-то вроде:

echo "a" > myapp20140626 95138.log

Где желательно следующее:

echo "a" > myapp20140626095138.log


6

adam_0
17 Июн 2016 в 03:25

Содержит ли путь, указанный в $ {OUPUT_RESULTS}, какие-либо символы пробела? Если это так, вы можете рассмотреть возможность использования ... >> "${OUPUT_RESULTS}" (используя кавычки).

(Вы также можете рассмотреть возможность переименования своей переменной в ${OUTPUT_RESULTS})


5

Thomas
30 Июн 2017 в 14:47

Если вы пытаетесь отладить эту ошибку «неоднозначного перенаправления» с помощью GitHub Actions. Я настоятельно рекомендую попробовать это следующим образом:

echo "MY_VAR=foobar" >> $GITHUB_ENV

Поведение, которое я испытал с $GITHUB_ENV, заключается в том, что оно добавляет его к переменным среды конвейера, как показано в моем примере MY_VAR


2

Steven Kotwal
6 Июл 2022 в 14:58

В моем случае это было полезным предупреждением, потому что целевая переменная (а не файл) была написана с ошибкой и не существовала.

echo "ja" >> $doesNotExist

В результате чего

./howdy.sh: line 4: $doesNotExist: ambiguous redirect


0

Frank Nocke
14 Мар 2021 в 14:30

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Ambiguous output redirect in xterm

Hi all,

I’ve been working on a bash script to help with backups that I have to do at work.

One of the lines in the script is supposed to launch an xterm, log into a specific server node and launch a tar backup to tape. This part works ok, but I’ve been trying to get stdout and stderr to… (2 Replies)

Discussion started by: Exitalterego

2. Linux

Ambiguous redirect error and syntax error when using on multiple files

Hi,

I need help on following linux bash script. When I linux commands for loop or while loop on individual file it runs great. but now I want the script to run on N number of files so it gives me ambiguous redirect error on line 12 and syntax error on line 22 : (pls help );

#!/bin/bash
#… (16 Replies)

Discussion started by: Madhusudan Das

3. Shell Programming and Scripting

Receiving ‘ambiguous redirect’ when trying to run command against multiple files

I came across the command string on https://www.unix.com/shell-programming-scripting/141885-awk-removing-data-before-after-pattern.html which was what I was looking for to be able to remove data before a certain pattern. However, outputting the result to a file seems to work on an individual basis… (4 Replies)

Discussion started by: HLee1981

4. Shell Programming and Scripting

ambiguous redirect error

This script has ambiguous redirect error.


cd $HOME
cd folder/work
# search all subfolders in work directory
find -mindepth 1 -maxdepth 1 -type d | while read directory
do
CUR_FOLDER=»${directory#»./»}»
cd $CUR_FOLDER
chmod 644 *

for ff in *; do
if ; then

(5 Replies)

Discussion started by: candyme

5. Shell Programming and Scripting

Ambiguous redirect

Hello there,

I’m totally new in bash programming and ran into my first problem.

My script should generate 3 textfiles where the content of the first and the third row are the same in each file. Only the second row is different.

This is what I did in a very simplified explanation:
(6 Replies)

Discussion started by: johndoe

6. UNIX for Dummies Questions & Answers

ambiguous redirect issue

I am trying to run the following script and I am getting an «ambiguous redirect» error. I have checked to make sure that the files are all where I have specified and are read/write as needed. Any ideas?

Note: I have removed the actual path info for privacy sake. I have triple checked to make… (1 Reply)

Discussion started by: malantha

7. Shell Programming and Scripting

> to empty files, but ambiguous redirect

Hi Everyone,

# ll
total 0
-rw-r—r— 1 root root 0 2010-05-13 11:29 a1.log
-rw-r—r— 1 root root 0 2010-05-13 11:29 a2.log
-rw-r—r— 1 root root 0 2010-05-13 11:29 a3.log

# rm a.log

above rm no problem, but when i use «> a.log», it says «-bash: a.log: ambiguous redirect».
(3 Replies)

Discussion started by: jimmy_y

8. Shell Programming and Scripting

Ambiguous output redirect error

Hi everyone, While I was trying to do

DATE=`date +»%Y%m%d_%H%M%S»`
STARTLOG=$TUXSTDDIR/start_$DATE.log
tmboot -y > $STARTLOG 2>&1

I got an error i.e. Ambiguous output redirect error. Here the first part is to boot the account so there is nothing wrong with that…. (6 Replies)

Discussion started by: pareshan

9. Shell Programming and Scripting

`ls -l`: Ambiguous

Hi,
I’m trying to code a simple script (c-shell) on a Solaris box and I’m getting an «Ambiguous» error. These are the lines that cause the error:

On c-shell:

> set var = «»
> @ var = `ls -l`
`ls -l`: Ambiguous

However if I change the second line to:

> set var = `ls -l`

This works… (2 Replies)

Discussion started by: Guillermo Lopez

10. UNIX for Dummies Questions & Answers

ambiguous redirect

i have following statement in the script

echo -e «$str_XML_col_name:$str_field_type;» >> $i_DC_Key_$i_Tgt_DC_key_Schema

here $i_DC_Key is DC key and $i_Tgt_DC_key are the variables……………

when i ran the script i am getting error rec_merge.sh: $i_DC_Key_$i_Tgt_DC_key_Schema:… (1 Reply)

Discussion started by: mahabunta

Получение ошибки «неоднозначного перенаправления»


Следующая строка в моем скрипте Bash

 echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  ${OUPUT_RESULTS}

дает мне эту ошибку:

 line 46: ${OUPUT_RESULTS}: ambiguous redirect

Зачем?



Ответы:


Иногда Bash может быть довольно тупым.

Следующие команды все возвращают разные сообщения об ошибках в основном для одной и той же ошибки:

$ echo hello >
bash: syntax error near unexpected token `newline`

$ echo hello > ${NONEXISTENT}
bash: ${NONEXISTENT}: ambiguous redirect

$ echo hello > "${NONEXISTENT}"
bash: : No such file or directory

Добавление кавычек вокруг переменной, кажется, является хорошим способом справиться с сообщением «неоднозначного перенаправления»: вы, как правило, получаете лучшее сообщение, когда допустили ошибку при наборе текста — и когда ошибка вызвана пробелами в имени файла, использование кавычек это исправить.




У вас есть переменная с именем OUPUT_RESULTSили это более вероятно OUTPUT_RESULTS?


michael@isolde:~/junk$ ABC=junk.txt
michael@isolde:~/junk$ echo "Booger" > $ABC
michael@isolde:~/junk$ echo "Booger" >> $ABB
bash: $ABB: ambiguous redirect
michael@isolde:~/junk$ 



поставить кавычки вокруг вашей переменной. Если в нем есть пробелы, он также даст вам «неоднозначное перенаправление». также проверьте свое правописание

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

например двусмысленного перенаправления

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file with spaces
aaaa     dddd         mol_tag




Недавно я обнаружил, что пробелы в имени файла перенаправления вызовут сообщение «неоднозначное перенаправление».

Например, если вы перенаправляете на application$(date +%Y%m%d%k%M%S).logи указываете неправильные символы форматирования, перенаправление не будет выполнено, например, до 10:00. Тем не менее, если вы использовали application$(date +%Y%m%d%H%M%S).logэто будет успешно. Это потому, что %kформат дает ' 9'9 утра, где %Hдает '09'9 утра.

echo $(date +%Y%m%d%k%M%S) дает 20140626 95138

echo $(date +%Y%m%d%H%M%S) дает 20140626095138

Ошибочная дата может дать что-то вроде:

echo "a" > myapp20140626 95138.log

где следующее — то, что было бы желательно:

echo "a" > myapp20140626095138.log



Содержит ли путь, указанный в $ {OUPUT_RESULTS}, какие-либо пробельные символы? Если это так, вы можете рассмотреть возможность использования ... >> "${OUPUT_RESULTS}"(используя кавычки).

(Вы также можете рассмотреть возможность переименования вашей переменной в ${OUTPUT_RESULTS})


У меня только что была эта ошибка в скрипте bash. Проблема была случайной в конце предыдущей строки, которая выдавала ошибку.


Еще одна вещь, которая может вызвать «неоднозначное перенаправление» — t n rэто имя переменной, которую вы пишете.

Может нет nr? Но ошибаться на стороне осторожности

Попробуй это

echo "a" > ${output_name//[$'tnr']}

Я получил удар при разборе HTML, Tabs tв начале строки.



Если редирект вашего скрипта содержит переменную, а тело скрипта определяет эту переменную в разделе, заключенном в круглые скобки, вы получите ошибку «неоднозначного перенаправления». Вот воспроизводимый пример:

  1. vim a.sh создать скрипт
  2. отредактировать скрипт, содержащий (logit="/home/ubuntu/test.log" && echo "a") >> ${logit}
  3. chmod +x a.sh сделать его исполняемым
  4. a.sh

Если вы сделаете это, вы получите «/home/ubuntu/a.sh: строка 1: $ logit: неоднозначное перенаправление». Это потому что

«Размещение списка команд в скобках приводит к тому, что создается подоболочка, и каждая из команд в списке выполняется в этой подоболочке без удаления неэкспортированных переменных. Поскольку список выполняется в подоболочке, назначения переменных не сохраняются. после завершения подоболочки «.

От использования скобок для группировки и расширения выражений

Чтобы исправить это, вы можете изменить сценарий на шаге 2, чтобы определить переменную вне скобок: logit="/home/ubuntu/test.log" && (echo "a") >> $logit


если вы используете имя переменной в команде оболочки, вы должны объединить ее со +знаком.

например :

если у вас есть два файла, и вы не собираетесь жестко кодировать имя файла, вместо этого вы хотите использовать имя переменной
"input.txt" = x
"output.txt" = y

затем («команда оболочки в кавычках» + x> + y)

это будет работать особенно, если вы используете это внутри программы на python с командой os.system, вероятно,


Это может быть так.

вы не указали файл в переменной и перенаправили вывод в него, тогда bash выдаст эту ошибку.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

Переменная out_file установлена ​​неправильно, поэтому следите за этим. Кстати, этот код печатает весь контент и его имя файла на консоли.


Я получил эту ошибку при попытке использовать расширение скобки для записи вывода в несколько файлов.

например: echo "text" > {f1,f2}.txtрезультаты в-bash: {f1,f2}.txt: ambiguous redirect

В этом случае используйте teeдля вывода в несколько файлов:

echo "text" | tee {f1,f2,...,fn}.txt 1>/dev/null

1>/dev/nullпредотвратит текст с записью на стандартный вывод

Если вы хотите добавить в файл (ы), используйте tee -a

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ambibox ошибка 404 при установке
  • Amaztools mi band 6 ошибка синхронизации c iphone