简体   繁体   中英

Escape within su and awk

#!/bin/bash
VM=`su joe -c "VBoxManage list vms | awk '{split($0,a,"\""); print a[2]; exit}'"`
echo $VM

I like to get the first VM name from joe's perspective. How do properly escape?

VBoxmanage list vms output is:

"VM 1" {serial num}
"VM 2" {serial num}

etc

Echo should ouput VM 1.

There are several ways round this. Here's one:

VM=$(su joe -c "VBoxManage list vms | awk -F'\"' '{print \$2; exit}'")

Instead of using split, just change the field separator. Depending on how many lines of output there are, the call to exit may not be necessary either. If there is only one line, awk will exit after it processes it anyway. I have also changed the backticks around the whole command to the preferred $() syntax.

VM=$(su joe -c 'VBoxManage list vms | cut -d \" -f2 | sed 1q')

You need to escape " and $ both:

VM=$(su joe -c "VBoxManage list vms | awk -F '\"' '{print \$2; exit}'")
echo "$VM"
VM 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM