How can I join elements of an array in Bash?

前端 未结 30 2441
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 12:05

If I have an array like this in Bash:

FOO=( a b c )

How do I join the elements with commas? For example, producing a,b,c.

30条回答
  •  悲&欢浪女
    2020-11-22 12:25

    In case the elements you want to join is not an array just a space separated string, you can do something like this:

    foo="aa bb cc dd"
    bar=`for i in $foo; do printf ",'%s'" $i; done`
    bar=${bar:1}
    echo $bar
        'aa','bb','cc','dd'
    

    for example, my use case is that some strings are passed in my shell script and I need to use this to run on a SQL query:

    ./my_script "aa bb cc dd"
    

    In my_script, I need to do "SELECT * FROM table WHERE name IN ('aa','bb','cc','dd'). Then above command will be useful.

提交回复
热议问题