Skip to content

Commit

Permalink
[builtins/printf] Validate the var name in the -v flag.
Browse files Browse the repository at this point in the history
Relevant to the conversation in issue #300.
  • Loading branch information
Andy Chu committed May 19, 2019
1 parent eee1ee1 commit 15cb0b0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
11 changes: 10 additions & 1 deletion osh/builtin_printf.py
Expand Up @@ -18,6 +18,7 @@
from core import util
from core.util import p_die
from frontend import args
from frontend import match
from frontend import reader
from osh import builtin
from osh import state
Expand Down Expand Up @@ -250,7 +251,15 @@ def __call__(self, arg_vec):

result = ''.join(out)
if arg.v:
state.SetStringDynamic(self.mem, arg.v, result)
var_name = arg.v

# Notes:
# - bash allows a[i] here (as in unset and ${!x}), but we haven't
# implemented it.
# - TODO: get the span_id for arg.v!
if not match.IsValidVarName(var_name):
raise args.UsageError('got invalid variable name %r' % var_name)
state.SetStringDynamic(self.mem, var_name, result)
else:
sys.stdout.write(result)
return 0
20 changes: 20 additions & 0 deletions spec/builtin-printf.test.sh
Expand Up @@ -50,6 +50,26 @@ OK
## N-I dash stdout-json: ""
## N-I dash status: 1

#### printf -v a[1]
a=(a b c)
printf -v 'a[1]' %s 'foo'
echo status=$?
argv.py "${a[@]}"
## STDOUT:
status=0
['a', 'foo', 'c']
## END
## N-I mksh/zsh STDOUT:
-vstatus=0
['a', 'b', 'c']
## END
## N-I dash/ash stdout-json: ""
## N-I dash/ash status: 2
## N-I osh STDOUT:
status=2
['a', 'b', 'c']
## END

#### dynamic declare instead of %s
var=foo
declare $var='hello there'
Expand Down
2 changes: 2 additions & 0 deletions test/parse-errors.sh
Expand Up @@ -242,6 +242,8 @@ printf-builtin() {
set +o errexit
_error-case 'printf %'
_error-case 'printf [%Z]'

_error-case 'printf -v "-invalid-" %s foo'
}

other-builtins() {
Expand Down

0 comments on commit 15cb0b0

Please sign in to comment.