我正在尋找一種標準工具,它能夠將所有參數取出並將其轉換爲適合用作多個參數的單個字符串自動生成的bash/sh/zsh腳本。這樣的命令在script-fu的各個學科中非常有用。在另一個腳本中使用它用標準工具轉義整個參數在sh-like shell中使用
% shsafe 'A big \nasty string '\'' $HOME $PATH' 'another string \\'
'A big \nasty string '\'' $HOME $PATH' 'another string \\'
:其使用的一個例子
% sshc host rm 'file/with spaces and $special chars'
其中sshc
包含
#!/bin/bash
# usage: sshc host command [arg ...]
# Escapes its arguments so that the command may contain special
# characters. Assumes the remote shell is sh-like.
host=$1
shift
exec ssh "$host" "$(shsafe "[email protected]")"
又如:
#!/bin/bash
# Run multiple commands in a single sudo session. The arguments of
# this script are passed as arguments to the first command. Useful if
# you don't want to have to type the password for both commands and
# the first one takes a while to run.
sudo bash -c "pacman -Syu $(shsafe "[email protected]") && find /etc -name '*.pacnew'"
我做不到找一個合適的在已有的命令中解決這個問題,所以我編寫了我自己的,名爲shsafe
。它使用單引號''
絕對關閉所有外殼擴展的事實,除了'
本身。
shsafe
:
#!/usr/bin/env python
from sys import *
n = len(argv)
if n == 1:
exit(0)
i = 1
while True:
stdout.write("'" + argv[i].replace("'", "'\\''") + "'")
i += 1
if i == n:
break
stdout.write(' ')
stdout.write('\n')
是否有任何標準的工具能夠這樣做是爲了它的參數呢?
注意,它使用由剛%Q格式的格式字符串printf命令是不是這個不夠好,因爲它不會讓多個參數分隔:
% printf %q arg1 arg2
arg1arg2
'printf「%q」arg1 arg2'? 'printf「%q」「arg1 arg2」'? – 123
我想到了。即使有空間,arg1和arg2也會被視爲相同的參數,並以空格分隔。 'printf'$''''%q''''arg1 arg2'確實有效。然而,這是非常容易出錯的,每次都必須輸入。我不認爲這是一個足夠好的解決方案,即使它只使用標準工具。 – enigmaticPhysicist
你的意思是'$'\'%q \'''?打印時如何查看字符串? – 123