Objective-C shell shielding

How to avoid arguments for shell commands in ObjectivesC?

The ruby ​​library has Shellwords ( shellescape for NSString, shelljoin for NSArray, I don't need shellsplit ). And I really need an escaped string, I know about NSTask, I don't need to execute this command.

+4
source share
2 answers

Content exclusion for the shell is pretty simple if you use single quotes. The important thing to understand about quoting a shell is that you can concatenate strings with different styles of quotes and even strings without quotes in the same argument. For example, 'one two'three" four" mixes all 3 citation styles and finishes passing the string "one fourth four" as the only argument. Another thing to understand is that outside of the quote you can discard special characters. The end result is a string of type 'one two'\''three four' , which evaluates to the string "one two-three four", with one quote. Using this trick, you can easily quote any string by replacing all single quotes with the sequence '\'' and then wrapping the entire string in one pair of single quotes.

If you have the following line:

 I don't like shell quoting 

and you apply this simple transformation, you get

 'I don'\''t like shell quoting' 

and this gets an estimate of the original string by the shell and is treated as a single argument.

The following category in NSString should easily perform this conversion:

 @implementation NSString (ShellQuoting) // prefixed with "my", replace with your prefix of choice - (NSString *)myStringByShellquotingString:(NSString *)str { NSMutableString *result = [NSMutableString stringWithString:str]; [result replaceOccurrencesOfString:@"'" withString:@"'\\''" options:0 range:NSMakeRange(0, [result length])]; [result insertString:@"'" atIndex:0]; [result appendString:@"'"]; return result; } @end 
+4
source

See the list of NSString methods here . There are many obscure, but I do not think this is suitable for your work. You need to write it yourself.

If this method is called relatively rare, I simply call ruby binary from within Objective-C and use shellescape and then retrieve the result; stupid to digest the wheel.

0
source

Source: https://habr.com/ru/post/1336405/


All Articles