添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

In bash how can I make a construction like this to work:

if (cp /folder/path /to/path) && (cp /anotherfolder/path /to/anotherpath)
  echo "Succeeded"
  echo "Failed"

The if should test for the $? return code of each command and tie them with &&.

How can I make this in Bash ?

@Dragos, lose the parentheses; all they do is spawn an extra subshell (almost certainly not what you want.) – vladr Mar 26, 2010 at 4:03
if cp /folder/path /to/path /tmp && cp /anotherfolder/path /to/anotherpath ;then
  echo "ok"
  echo "not"
cp /folder/path /to/path && cp /anotherfolder/path /to/anotherpath
if [ $? -eq 0 ] ; then
    echo "Succeeded"
    echo "Failed"
                @Dragos: The last command, a complex command in this case, it the cp && cp. If the first exits non-zero $? gets that. If the second exits non-zero then $? gets that. Otherwise $? gets zero (and both exited zero). But this is a useless use of $? since the commands can be put directly in the if.
– Chris Johnsen
                Mar 24, 2010 at 14:40
                @Vlad, there is no pipe (|) involved. My “complex command” comes from the dash manual. linux.die.net/man/1/dash Other sets of documentation (POSIX: opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html ; and bash: gnu.org/software/bash/manual/bashref.html#Lists ) do not include the same idea of a “complex” command. The one && two construct is called a list command consistently though.
– Chris Johnsen
                Mar 26, 2010 at 6:47
                Sorry, yes, "list" is what I was looking for.  I'll take the POSIX nomenclature over dash any time. :)
– vladr
                Mar 26, 2010 at 6:56

I tested it :

david@pcdavid:~$ cp test.tex a && cp test.aux b && { echo "haha"; } || { echo "hoho"; }
david@pcdavid:~$ cp test.ztex a && cp test.aux b && { echo "haha"; } || { echo "hoho"; }
cp: cannot stat `test.ztex': No such file or directory
david@pcdavid:~$ cp test.tex a && cp test.zaux b && { echo "haha"; } || { echo "hoho"; }
cp: cannot stat `test.zaux': No such file or directory
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.