質問

I have a bash function that takes a param, runs it through JS Lint, then outputs the result into a file on the Desktop. This works so long as you're in the directory of the JS file when you run it. However if you pass the function a path it chokes. jslint is the name of my function. Examples:

# This works
$ jslint script.js

# This doesn't work
$ jslint ~/dev/project/js/script.js

# Neither does this
$ jslint /Users/Jesse/dev/project/js/script.js

In my function I need to take $1 and trim off the path when I go to output it preferably using regular expressions. See my function below:

function jslint {
    /usr/local/bin/node /usr/share/node-jslint/node_modules/jslint/bin/jslint.js $1 > "~/Desktop/" + $1 + "-lint.txt"
}

Here's am example error from a project I am working on and tried to run it on:

-bash: /Users/Jesse/Desktop/Dropbox/dev/ourcityourstory.com/js/script.js-lint.txt: No such file or directory

役に立ちましたか?

解決

You don't need a regex. Bash supports simple glob patterns for trimming prefixes/suffixes. This can be done with ${1##*/}, which trims everything up to the last / from the variable.

Specifically, there are 4 variants:

  1. ${var#pat} treats pat as a glob and trims the shortest matching prefix from var.

  2. ${var##pat} treats pat as a glob and trims the longest matching prefix from var.

  3. ${var%pat} treats pat as a glob and trims the shortest matching suffix from var.

  4. ${var%%pat} treats pat as a glob and trims the longest matching suffix from var.

In your specific case, you'll probably want to say

function jslint {
    /usr/local/bin/node /usr/share/node-jslint/node_modules/jslint/bin/jslint.js "$1" > "~/Desktop/" + "${1##*/}" + "-lint.txt"
}

(I've also quoted the variable, which is necessary if the path contains spaces)

他のヒント

Instead of regex - what about basename which outputs the string from the last '/' of the file path parameter.

e.g. basename /usr/include/stdio.h  --> stdio.h
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top